...

/

The useState Hook Flow in React

The useState Hook Flow in React

Learn about the significance of prop passing and lifting up patterns for building robust and maintainable applications.

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

Press + to interact
The Hello World counter
The Hello World counter

We can capture this UI behavior in a Title component:

const Title = () => {
// State hook to manage the count state
let [count, setCount] = useState(0);
// Event handler function triggered on button click
const onClick = () => {
setCount(count + 1);
};
// JSX rendering with a button and an h1 element
return (
<>
<button onClick={onClick}>+</button>
<h1>Hello World+{count}</h1>
</>
);
};
Title component using the useState hook to manage a count state and update it upon button click

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 state
let [count, setCount] = useState(0);
// Event handler function triggered on button click
const onClick = () => {
setCount(count + 1);
// Log a message to the console indicating the click event and the current count
console.log('clicked', count); ➀
};
// Log a message to the console indicating the component render and the current count
console.log('rendered', count); ➁
return ...
}
Function component 'Title' utilizing the useState hook to manage a count state
...