Understanding useState Hook in 3 min
Use state without writing a class.
First, Hooks!
A Hook is a special function that lets you “hook into” React features.
In simple terms, Hooks are functions that make React state and lifecycle features accessible without writing any class component.
Basic Hooks include useState, useEffect, and useContext. For this article, we will focus on the useState hook and explore how to declare, read and update state variable in a functional component with the useState hook.
useState Hook?
You might have faced an issue where you would have written a functional component and realized that you need to add some state to it and then ended up converting it to a class component. Well, not anymore. State hook is here to the rescue.
usestate
is the Hook that lets you “hook into” React state. With the help of useState hook, a state can be added to a functional component.
Let's take an example where we initialize a state variable count
to 0 in a functional component by calling a usestate
hook.
import React, { useState } from 'react';function Example() {
const [count, setCount] = useState(0);
}
Now let's understand what exactly const [count, setCount]=useState(0);
is actually doing.
- Calling
useState
will declare acount
state variable. - The only argument to the
useState()
hook is the initial state. So here we are setting the initial state ofcount
to 0. - The
useState
returns pair of values: the current state and a function that updates it. With the help of array destructing,count
is set to the first value returned byuseState
andsetCount
to the second. This means the current state is assigned tocount
whereas the function that updates the state is assigned tosetCount
.
You can declare multiple state variables with useState
hook.
import React, { useState } from 'react';function Example() {
const [count, setCount] = useState(0);
const [status, setStatus] = useState('active');
const [list, setList] = useState([1,2]);
}
Reading State
Reading state in a functional component is straightforward. You can directly use the count
state variable that you declared earlier, with the help of a useState hook.
import React, { useState } from 'react';function Example() {
const [count, setCount] = useState(0);
return <p>You clicked {count} times</p>;
}
Updating State
If you remember, the second value returned from the useState hook is a function that updates declared state variable. So you can directly use setCount
to update the count
state.
import React, { useState } from 'react';function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
However, unlike this.setState
in a class, updating a state variable always replaces it, instead of merging it.
Note: Before using hooks read “Rules of Hooks”.
That's it!.