The useState Hook Flow in React
Explore the flow of the useState hook in React components to manage dynamic user interactions. Understand how to update state locally and pass state changes from parent to child components. Learn the concept of lifting state to a parent component to enable data sharing across siblings, enhancing your React state management skills.
We'll cover the following...
User interactions with the state
A state is one of the most common techniques in React for driving user interactions. Let's consider a component with a button. Each time we click the button, it increments a number and appends it to the Hello World string (see the image below).
We can capture this UI behavior in a Title component:
const Title = () => {// State hook to manage the count statelet [count, setCount] = useState(0);// Event handler function triggered on button clickconst onClick = () => {setCount(count + 1);};// JSX rendering with a button and an h1 elementreturn (<><button onClick={onClick}>+</button><h1>Hello World+{count}</h1></>);};
Here, we use [count, setCount] to keep track of the count state. Then, we display count in the h1 element of the page and dispatch setCount in the click handler of the button element. Each time the button is clicked, it should increment the count value.
To confirm what happened under the hood, let's add console.log to two locations:
function Title() {// State hook to manage the count statelet [count, setCount] = useState(0);// Event handler function triggered on button clickconst onClick = () => {setCount(count + 1);// Log a message to the console indicating the click event and the current countconsole.log('clicked', count); ➀};// Log a message to the console indicating the component render and the current countconsole.log('rendered', count); ➁return ...}
The first one is placed after setCount to ...