useState
is a Hook that needs to be called inside a function component to add some local state to it. React will preserve this state between component re-renders.
There are many use cases for the useState
hook, but in this article, I will focus on the following five:
useState
use casesLet's start with a warning: don't write code in this way, because it will create an infinite loop:
import { useState } from "react";
const UseCaseStateManagement = props => {
const [state, setState] = useState('initial value');
setState('new value');
console.log(state);
return (
<>
<h2>useState use case</h2>
<h3>State management</h3>
<hr />
<p>{state}</p>
</>
);
};
export default UseCaseStateManagement;
The loop is created because the initial render calls the state update function setState
, which in time triggers a re-render and a new function evaluation.
If we want to change a state due to an action performed by the user, we can do this:
import { useState } from "react";
const UseCaseStateManagement = props => {
const [state, setState] = useState('initial value');
console.log('🔄 This is a re-render');
const clickHandler = () => {
setState('new value');
};
return (
<>
<h2>useState use case</h2>
<h3>State management</h3>
<hr />
<button onClick={clickHandler}>Set state</button>
<p>{state}</p>
</>
);
};
export default UseCaseStateManagement;
That state will be preserved across component re-renders and we will be able to make use of it in the newest re-render.