There are many answers online explaining why we probably don't need derived state, but what is it exactly? Where is it being "derived from"? Why does it matter, and how is it different from the correct way of handling state in a react app?
The state is a built-in React object that is used to contain data or information about the component. A component's state can change over time; whenever it changes, the component re-renders.
The getDerivedStateFromProps() method is used when the state of a component depends on changes of props. getDerivedStateFromProps(props, state) is a static method that is called just before render() method in both mounting and updating phase in React. It takes updated props and the current state as arguments.
React state has a very important relationship with rendering components. Whenever we return JSX from a React component, when that component is used, it will be rendered and therefore displayed in our application. React takes care of this rendering process.
State is the main attribute of react native which is mutable in nature(which means its values can be changed inside the component), it gives a powerful mechanism to manage the data available inside any component from start to end of the component life cycle (state is object containing all the data required to create ...
Derived state is a state which mainly depends on props.
static getDerivedStateFromProps(props, state) {
if (props.value !== state.controlledValue) {
return {
controlledValue: props.value + 1,
};
}
return null;
}
In the above codes, controlledValue
is a derived state which depends on value
prop.
Then why we avoid to use these derived states?
The answer is simple: To reduce needless re-rendering.
In details, as we know, when any prop or state is changed then it will make the component to re-render. Then let's assume that value
props is changed in the above codes, then it will try to re-render the component and also controlledValue
state is also updated. That will also try to re-render.
So in fact, for only one update for a prop, but two re-renders.
Example:
render() {
return (
<div>
<span>{this.state.controlledValue}</span> // same as this.props.value + 1
</div>
);
}
The two lines of output will be same, but when the prop is changed the component should be re-rendered twice.
But If we calculate output value from prop then, We don't need this controlledValue
state. Then the component will be re-rendered only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With