DEV Community

Cover image for Introductory to useState
YarixaR
YarixaR

Posted on

Introductory to useState

Finishing up my second phase of a boot camp, I thought I'd write a short post on React hooks. Specifically, useState.

The hook, useState is a function that React provides for us and it allows us to give our component some state.

What is state?
State is data that changes over time as the user interacts with your app.

How do we update state?
By using React's useState function of course!

useState will return an array that has two variables inside of it.

  1. State. Name the variable as a reference to the value of the state.
  2. setState. This is a function returned by useState that re-renders the component caused by changes to the state.
const [ state, setState ] = useState('initial State')
Enter fullscreen mode Exit fullscreen mode

useState has a parameter that determines the initial value of that state. It takes a boolean, string, and number.

Warning! Learn from me...

  • Call hooks at the most top level of a React function component, before a return.

  • Call hooks from custom hooks like useEffect.

Image description

Let's make a count button.

First, we need to import useState from React to use our function.

import React, { useState } from 'react'

const App = () => {

const [ count, setCount ] = useState(0)

    return(
       <div>
         <button>Click to show count</button>
       </div>
)
}
Enter fullscreen mode Exit fullscreen mode

During the initial render, the returned state (count) is the same as the value passed as the first argument (0). The setCount function is used to update the state. It accepts new state value and re-renders the component.

We will need to add an event listener and another function to help us update the value of count whenever the button is clicked.

import React, { useState } from 'react'

const App = () => {

const [ count, setCount ] = useState(0)

const increaseCount = () => {
  setCount( count + 1 )
           /* 0 + 1 */
}

    return(
       <div>
         <button onClick= { increaseCount }>
             Click to show { count }
         </button>
       </div>
)
}
Enter fullscreen mode Exit fullscreen mode

Above, you see that onClick function that will tell the button what to do when clicked.

When clicked, it runs the function (increaseCount).

Running the function, calls setCount and tells React that the state, count's value has to update to 1.

Sources:
“Home.” Flatiron School, 9 May 2022, https://flatironschool.com/.

“React Interactivity: Events and State - Learn Web Development: MDN.” Learn Web Development | MDN, https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state.

Top comments (0)