Understanding the useState syntax in React
Published on 5th May 2022
If you have started a new React application recently then you have probably been introduced to hooks. By far the most commonly used hook is the useState hook.
The typical syntax for using the useState
hook looks something like this:
const [count, setCount] = useState(0);
Many people new to React, or JavaScript for that matter, may find this syntax confusing. You can probably get quite far without fully understanding it, however it is always best to understand as much as you can about the code you are writing.
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 useState
hook.
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[0];
const setCount = counter[1];
Hopefully this helps you to understand why the commonly used syntax for the useState
hook works, and maybe even encourages you start your journey into learning more advanced JavaScript features.