React state
“setState” method
Every time the state changes, React runs the render function again.
However, in some cases, we may want to perform some operations when the state is updated, and React provides a callback for that as follows:
this.setState({ clicked: true }, () => { console.log('the state is now', this.state); });
If we pass any function as a second parameter of the setState method, it gets fired when the state is updated, and the component has been rendered.
Asynchronous
The setState function should always be considered asynchronous
handleClick() { this.setState({ clicked: true, }); console.log('the state is now', this.state); } render() { return <button onClick={this.handleClick}>Click me!</button>; }
The preceding snippet now renders the state as null, old state value.
Using the state
Only the minimal amount of data needed should be put into the state
For example, if we have to change a label when a button is clicked, we should not store the text of the label, but we should only save a Boolean flag that tells us if the button has been clicked or not.
Add to the state only the values that we want to update when an event happens, and for which we want to make the component re-render
In general, we should store into the state only the information needed to keep track of the current user interface state, such as the currently selected tab of a tabbed menu.
Check if the data we are persisting is needed outside the component itself or by its children.
If multiple components need to keep track of the same information, we should consider using a state manager such as Redux at the application level.
Only store in the state values that we are using inside the render method
React Hooks
React Hook let us use state, and other React features, without writing a class componentDidMount
import React, { useState } from 'react'; function Counter() { // times is our new state variable and setTimes the function to update that state. const [times, setTimes] = useState(0); // 0 is the initial value of times return ( <div className="Times"> <p>Times clicked: {times}</p> <button onClick={() => setTimes(times + 1)}>Click it!</button> </div> ); } export default Counter;
Leave a Reply