Skip to content

getDerivedStateFromProps for asynchronous setState #1147

Closed
@flahertyb

Description

@flahertyb

I am inquiring about what is hopefully an undiscussed use case related to the componentWillReceiveProps -> getDerivedStateFromProps changes. I read through the blog post and threads like #721.

The use case is a button which says either "Save", "Saving", or "Saved!". The idea is that the button component is shared across apps, which pass a prop to the button indicating whether the app is currently saving. The button component's purpose is to encapsulate the logic that temporarily shows the text "Saved!", when saving finishes.

This can be handled with componentWillReceiveProps pretty simply: https://jsfiddle.net/Luktwrdm/1137/ - if the status prop changes in a certain way, show the "Saved!" text, and then use a timeout to later change itself back to a ready state ("Save").

Without componentWillReceiveProps, this case seems to require both getDerivedStateFromProps and componentDidUpdate, and an extra key in the state: https://jsfiddle.net/Luktwrdm/1138/ - You can't do it all in didUpdate because otherwise the component would flash with the incorrect copy for a split second. And you can't do it all in getDerivedStateFromProps because it's static.

The purpose of this issue is to clarify - is this (the second fiddle) now the best way to handle such a situation? Am I missing some higher level structural way to avoid this complexity?

I can imagine other use cases, like notifications, where it might make sense for a component to react to its props changing by making a temporary state change. Is that an anti-pattern? Or something worth covering in the docs?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions