Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is derived state in React, and why is it important?

Tags:

reactjs

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?

like image 291
Tycholiz Avatar asked Oct 08 '19 14:10

Tycholiz


People also ask

What is the importance of state in React?

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.

What is the use of get Derived state from props?

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.

Is state necessary in React?

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.

What is the purpose of react native states?

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 ...


1 Answers

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.

like image 159
Diamond Avatar answered Oct 13 '22 21:10

Diamond