What is the method for updating state in React?
In React, the method used to update state is by using the setState() method. It is a method within the Component class that is used to update the component’s state, accepting either an object or a function as a parameter to specify the state value to be updated.
When using an object as a parameter, setState() will merge the properties of the object with the current state and trigger a re-render of the component. Here is an example code:
this.setState({ count: this.state.count + 1 });
When using a function as a parameter, setState() will pass the current state as an argument to the function and return a new state object. Sample code is shown below:
this.setState((prevState) => {
return { count: prevState.count + 1 };
});
After calling the setState() method, React will merge the new state into the component and trigger a re-render of the render() method, updating the component’s view.