Understanding React useState

Hi, in this post we are going to understand how the useState works and we are going to see some examples.

The useState is part of React special functions called “hooks” and we can call those functions inside our custom component to store data (like a state) or perform actions (or side-effects).

Each of this special functions (useState, useEffect, useContext, useRef, useReducer and more) has a unique API, one of those special functions return a values, other return pair of values and others nothing at all.

useState

The useState function accept a single argument and that argument is the initial state for the component.

// Dependencies
import React, { useState } from 'react'

// The useState function with the argument
// The state will start as 0
useState(0)

The useState function returns a pair of values by returning an array with two elements like this:

const array = useState(0)
const count = array[0]
const setCount = array[1]

We use destructuring syntax to assign each of those values to distinct variables.

// Destructuring format
const [count, setCount] = useState(0)

 The state value (count) and the second is a function (setCount) we can call to update the state.

// Dependencies
import React, { useState } from 'react'
 
// Array with two elements
const [count, setCount] = useState(0)

Note:  Those variables (count and setCount) can be named these as whatever we want, but commonly we assign similar names for the state value and then we assign the prefix set to the function (setCount)

What is the state?

The state is the data that changes over time.

Let’s see this example that is incrementing a number (1 by 1) when user click a button.

// Dependencies
import React, { useState } from 'react'

// The useState with the initial state as 0 
// The state (count) and the function (setCount) that update the state
const [count, setCount] = useState(0)

// Method that is called by the onClick(button)
const increment = () => setCount(count + 1)

// Rendering the state in Html
return <button onClick={increment}>{count}</button>

View: here the button with 0 as initial state

When user click that button then the value increment 1 by 1, so 0, 1, 2, 3, 4, etc.

Explanation

When the button is clicked, the  increment function will be called at which time we update the count y calling setCount.

When setCount is called then that means that React will re-render the component (and that’s why we are seeing different printed values in the browser), the entire component is re-run so when useState is called this time the value we get back is the new value and continues until the component is unmounted (removed from the Application or user close the Application)

By Cristina Rojas.