Understanding the useState hook in React with Basic Usage | Hacker Noon

Author profile picture


Full-Stack Web Developer

useState is a React hook function that allows us to use state and other React features without writing a class. In React every function name begins with “use”.

For example


is a React hook. I came across hooks when I was building my final capstone project. I got stuck for days because the concept was not clear for me in the beginning. After watching a video by JohnSmilga on freecodecamp,I started to understand more. I will share a link for the video at the end of the article. 

Let’s get going

The first thing to do is to import “useState” from react

import React, { useState } from 'react'

“useState” function returns a value and a function. The value to hold state and the function to manipulate the state.

This is how we setup useState:

const [name, setName] = useState('Daniel')

In this case, the name will be the value and setName is the function. It is a covention to begin the function name with “set” then followed by the value name (CamelCase) . “useState” can be called with a default value, otherwise the value will return “undefined”.

To check the value of the name:

console.log(name) => Daniel

So what we did is to set the state value with the default value “Daniel”. We can change the name value and check the console.

To be able to change the value of the name variable, we need to invoke our “setName” function. Here is how we change state value in react

console.log(name) => Lydia

Now when we console.log(name). We expect the string “Lydia”

Here is a code implementation of “useState” with a “counter” example:

import React, { useState } from 'react';

const UseStateCounter = () => {
  const [value, setValue] = useState(0);

  const reset = () => {
  return <>
      <button onClick={ () => setValue(value + 1)}>increase</button>
      <button onClick={ reset }>reset</button>
      <button onClick={ () => setValue(value - 1)}>decrease</button>

export default UseStateCounter;

Thank you for taking the time to read my article. I hope it helps. If you need more detailed concepts about React.

Kindly check out the link below:

This video tutorial explains more advance react concepts. I urge you to take a look.

If you liked this article, kindly click on the clap icon. Happy coding. You might also want to check out:



Join Hacker Noon

Create your free account to unlock your custom reading experience.

read original article here