Understanding the useState syntax in React
Published on 5th May 2022
The typical syntax for using the
useState hook looks something like this:
const [count, setCount] = useState(0);
The syntax used for the
useState hook is called destructuring assignment which was introduced as part of ES2015.
Whilst you can read more about destructuring assignment, I wanted to cover how it works in relation to the React
What is happening is that when you call
useState it returns an array with the state value as the first item and the setter function as the second item.
Essentially you could replace the above syntax with:
const counter = useState(0);
const count = counter;
const setCount = counter;
Hopefully this helps you to understand why the commonly used syntax for the