In this tutorial, we would learn about the State Hook. This allows use to use state within a functional component.
1. Example Using Class Component
To make our understanding of the State Hook solid, we’ll first create a class component. Then we create the equivalent using State Hook.
This component would be a counter component similar to what we have in the introduction.
The counter using class component is given below. I call it ClassCounter.
import React, { Component } from 'react' class ClassCounter extends Component { constructor(props) { super(props) this.state = { count: 0 } } incrementCount = () => { this.setState ({ count: this.state.count +1 }) } render() { const {count} = this.state; return ( <div> <p>You clicked {count} times</p> <button onClick={this.incrementCount}>Click Here!</button> </div> ) } } export default ClassCounter
You can notice from this example that there are three steps needed to create this counter component.
- create component
- create a state variable initialized to 0
- create a method that would set this state value
2. Counter Using the State Hook
We’ll follow the same step. First we create a functional component. However since it’s a functional component, we can’t use state like in class component. So we’ll do the following:
First import the useState() function from react
import {useState} from 'react'
Next, call the useState() function. The useState() function() accepts the initial value of the state property as argument. Then it returns a pair of items: the current value of the state property and a method that updates the state property. So these return values are then assigned to two variables using array destructuring.
const [count, setCount] = useState(0)
Finally, we now use these variables in the JSX. On the button click, we simply call the method, setCount() and pass it the incremented value of the count variable (count+1).
The complete code is shown below:
import React from 'react' import {useState} from 'react' function HookCounter() { const [count, setCount] = useState(0) return ( <div> <p>You have clicked {count} times</p> <button onClick={()=>setCount(count +1)}> Click Here </button> </div> ) } export default HookCounter
So you can now include this in your App component.
3. How State Hook Works
- When the component is first created and rendered, a state variable is created and initialized to an initial state of 0. This initial value is not used during re-rendering.
- When the button is clicked, the setCount() method is called which increments the state from 0 to 1
- The setCount method would now force the component to re-render
- After re-rendering, the new state of 1 is then rendered in the browser.
Some rules to followed are:
- Hooks are only to be called at the top level. Not be called inside loops, conditions or nested functions
- Hooks are only called from functional components
In the next part, we look at how to implement Hooks with previous state, objects and arrays.