Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare with previous props in getDerivedStateFromProps

Tags:

reactjs

Think of a component that has a prop 'name' and state 'elapse'.

new Component(name) => "Hi {name}. It's been {elapse} seconds"

{elapse} should be reset to 0 when the prop {name} changes.

If the prop changes from 'Alice' to 'Bob' at 10 seconds, the message should change from

Hi Alice. It's been 10 seconds

to

Hi Bob. It's been 0 seconds

  • getDerivedStateFromProps cannot be used because {elapse} is not a pure function of {name}, and I cannot return 0 because it may be called on re-render.

  • componentDidUpdate will eventually update {elapse} to 0, but before that, the invalid state "Hi Bob. It's been 0 seconds" is shown to the user.

Can getDerivedStateFromProps or componentDidUpdate implement this scenario?

  1. In many cases the state is not a pure function of props. Is getDerivedStateFromProps only for stateless functional components? Does react encourage the use of stateless components?

  2. How can getDerivedStateFromProps replace componentWillReceiveProps in stateful components?

like image 986
mq7 Avatar asked Apr 08 '18 21:04

mq7


People also ask

How do you get previous props in React class component?

In React class components, we had the componentDidUpdate method, which provided the previous prop and state arguments. Now, with functional components, we have effects. In order to accomplish saving the previous state and prop values, we can store them to a ref.

Is getDerivedStateFromProps deprecated?

There are a few life cycle methods that have been deprecated and renamed in React 17. We don't need to use these anymore— getDerivedStateFromProps and getSnapshotBeforeUpdate essentially replaced them.

Can we update state in getDerivedStateFromProps?

ReactJS – getDerivedStateFromProps() MethodThis method is majorly used to update the state, before the rendering of the component, which depends upon the props received by the component. This method is called on every rerendering of the component.

What is the replacement for componentWillReceiveProps?

The useEffect hook is also the equivalent of the componentWillReceiveProps or componentDidUpdate hooks. All we have to do is to pass in an array with the value that we want to watch for changes.


1 Answers

If you look around you'll see you're not the first one having this problem - it was thoroughly discussed on github 1 2 3 and in a thread on hackernews here. The recommended solution is to mirror the props you need to check in the state:

state = { name: "", lastTime: Date.now() }

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.name !== prevState.name) {
        return { name: nextProps.name, lastTime: Date.now() };
    }
    return null;
}
like image 114
Al.G. Avatar answered Sep 20 '22 17:09

Al.G.