React is the leading frontend framework. They recently released a new way to write React components by using a function instead of class. This new method allows developers to keep the ease of function and still have the deepness of React lifecycle by using hooks.
Let’s see how to use the useState
hook.
The useState
React hook is used to replace this.state
. This hook is used to add a React state to a function.
Simple use of useState
would be :
import React, { useState } from "react"; const Counter = () => { const [counter, setCounter] = useState(0); return ( <div> <h1>{counter}</h1> </div> ); }; export default Counter;
Here we initialize a state counter
that will be initialized with the value 0
when the component mount.
Let’s see how to increment and update the state of counter
using the method from useState
.
We can see that we initialized the counter
state but also declared a const setCounter
. It’s a function that allows us to change the counter
state:
import React, { useState } from "react"; const Counter = () => { const [counter, setCounter] = useState(0); const incrementCounter = () => { setCounter(counter + 1); } return ( <div> <h1>{counter}</h1> <button onClick={() => incrementCounter()}>Increment</button> </div> ); }; export default Counter;
Now when we press the button, it launch the incrementCounter()
function that use setCounter
declared by the useState
hook.
Changing the state of counter
triggers React to re-render the component to show the change.
So the useState
hook allows us to declare stateful values and change them to trigger React lifecycle. In this example, we change a local state, but let’s see how to handle a fetch from a database using useEffect
in a second article.