An overview of the

This article mainly discusses the use of state and setState in React.

define

State can be thought of as a collection of data in the React component that is used to record mutable state in the component, that is, data that can be modified in the component.

So how do you determine if a variable is suitable as data in a state?

Component State requirements

In the component, there are the following requirements for state data:

  • State can represent the complete set of states presented by the component: All state changes of the component can be reflected in state
  • State can represent the smallest set of states that a component can present: all data in state represents changes to the component, with no redundant states and no intermediate states that need to be computed from other states

The difference between State and Props

  • State is used to represent component changes and is mutable in the current component
  • Props is passed in from the parent component and is read-only in the current component

Can a variable be used as a criterion for State

Therefore, from the above description, we can judge whether a variable can be used as state from the following aspects:

  • Is the variable passed in by the parent component? If so, it cannot be used for state
  • Does this variable remain constant throughout the life of the component? If so, it cannot be used for state
  • Can this variable be evaluated by other state data or props? If so, it cannot be used for state
  • Is this variable used to render data in render? If not, it cannot be used for state

If a variable is not used as state, it is generally defined as a common property of the component, i.e. a variable such as this.name.

If a state is used by multiple components, you can upgrade the state to the parent component.

The State of the update

In the React. Instead of updating the state directly, we use setState() to update the state.

// Wrong update method
this.state.name = 'Joe';

// Correct update method
this.setState({name: 'Joe'});
Copy the code

Status updates can be asynchronous

For performance reasons, React can combine multiple setState() calls into a single call to improve performance.

Thus, this.state may be updated asynchronously, and you should not rely on their values to calculate the next state.

this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
Copy the code

We expected the count in state to increase by three times, but it might have increased by one.

Since this.state may be an asynchronous update, this.setstate () is simply setting the same value over and over again, the above code might be equivalent to:

const currentCount = this.state.count;
this.setState({count: currentCount + 1});
this.setState({count: currentCount + 1});
this.setState({count: currentCount + 1});
Copy the code

So, if we want the final answer to be 3, what can we do?

The usual way to do this is to change the first argument to this.setState() to a function that accepts the previous state as the first argument and props as the second argument when the update was applied:

this.setState((prevState, props) = > ({
  counter: prevState.currentCount + 1; })); .// Repeat 3 times
Copy the code

This.setstate () can be used with a second argument, which is an optional callback function that will not be executed until setState has been executed and the component has been redefined.

Status update merge

Updating the state is a shallow merge process, so when updating the state, only the changed state data is passed in, rather than the entire state data.

For example, your component’s state contains multiple variables:

constructor(props) {
    super(props);
    this.state = {
      title: 'hello world'.name: 'Joe'
    };
}
Copy the code

When you update the name property in state, just:

this.setState({name: 'bill'});
Copy the code

React merges the new name into the original state while retaining the original state title.

{
  title: 'hello world'.name: 'bill'
}
Copy the code

Status updates and Immutable

Immutable Data is Data that, once created, cannot be changed.

React officially recommends treating data in state as immutable. That is, when you want to execute this.setstate (), what you should do is create a new value to assign to the data in state.

This is partly because immutable objects are easy to manage and debug, and partly because when all state data is immutable, you can determine whether the state has really changed by comparing references to the state.

The following are described for different data types.

Number, string, Boolean, null, undefined

For the update of basic similar data, the update can be directly assigned.

this.setState({
    age: 20.name: 'bill'.success: true.addr: null.tags: undefined
});
Copy the code

object

Object – like subdivisions can be divided into narrow objects, arrays, functions

When state’s data is an array, a new array is assigned directly. To operate on yuan arrays, use the following methods:

var arr = this.state.arr;

/ / method
this.setState({ arr: [].concat(arr, ['arr1'])});/ / method 2
this.setState({ arr: [...arr, 'arr1']});/ / method 3
this.setState({ arr: arr.slice(1.3); });

4 / / method
this.setState({ arr: arr.splice(1.3.'arr1'); });
Copy the code

You can also iterate through arrays using methods like map, filter, and so on

When the data of state is an object in a narrow sense, the following methods can be used to modify the original object:

var obj = this.state.obj;

/ / method
this.setState({ obj: Object.assign({}, obj, {title: 'HELLO'}); });

/ / method 2
this.setState({ obj: {... obj,title: 'HELLO'}});Copy the code

Status updates and page rendering

Rerendering is triggered when the new state is different from the previous state. So this.setState() always triggers a page re-rendering. When this.setState() is called, the lifecycle hook function shouldComponentUpdate is fired. If this function returns false, rerendering is not triggered.

Additionally, we can use the this.forceUpdate() function to skip shouldComponentUpdate, forcing rerendering.

Refer to the link

  • State & Life Cycle, by React Chinese
  • In-depth understanding of State and setState()