TechMentorAI

useState Hook

in React JS

Published

useState is a Hook that allows you to add React state to function components. Hooks are functions that let you 'hook into' React features from function components. State is a concept in React that allows us to store values that a component may use or change over its lifecycle. In class components, we can use the this.state object to store values but in functional components, since there is no 'this' object, we use hooks like useState.

Imagine useState Hook in React JS

How to use useState Hook?

The useState hook takes one argument which is the initial state. It returns an array with two values. The first element is the current state, and the second element is a function that allows us to update the state.

const [state, setState] = useState(initialState);

useState Hook Example

Let's see an example. Here, we're creating a hooks-based counter. useState hook will return count as the current state and setCount as the function to change state.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;

Keep in mind that unlike this.setState in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function returned by useState with the spread (...) operator.

//In class component
this.setState({ ...oldValues, ...newValues });

//In functional component with hooks
setState(prevState => ({...prevState, ...newValues}));

No Time to Read? Learn on the Go!

By reading this article, you've invested 0.95 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.

Imagine you have a box of crayons. And each time you want to draw something, you can choose a different color. But after you choose it, you should remember which color it was, in case you want to use it again. useState Hook in React JS is like an invisible helper which helps you remember the color you chose. The 'color' can be anything - a number, a text, or even more complex things!

Imagine useState Hook in React JS

How do we use useState Hook?

When you use useState, you need to give it a starting color (but remember, it could be anything, not just a color!). Then it gives you two things: the current color, and a function that allows you to change the color. It’s like someone giving you the crayon you asked for and a magic button that can change the color of your crayon if you need.

const [color, changeColor] = useState('red');

What happens when you call changeColor?

When we press the magic button, or in other words, call the changeColor function, it tells our invisible helper to remember a new color. So the next time we ask for the color, we'll get the new one we gave him. For example, if we wanted to change the color from red to blue, we could call changeColor('blue').

changeColor('blue');

So, useState Hook is like an invisible friend who helps us remember things while we're drawing our picture (or building our website). Isn’t that fun and useful!

No Time to Read? Learn on the Go!

By reading this article, you've invested 1.22 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.

For more information, you can read about React Hooks and its different types

About author

Roman Y.
Senior Software Engineer at Nike

Why did I decide to launch this website? Drawing from my rich background in interviewing candidates for a variety of developer roles, I've observed a common pattern: many applicants share similar deficiencies in their knowledge during technical interviews. Motivated by this insight, I established this website with the aim of assisting developers in securing their ideal job. Through straightforward and concise articles, my goal is to not only deepen your understanding of programming language nuances but also to equip you with the insights needed to deliver the precise answers interviewers expect. Essentially, you'll be providing the correct response. I encourage you to spread the word about this site on social media platforms. Echoing the wisdom of an Armenian saying: "Do good and cast it into the water."

EXCLUSIVELY

Certain articles only distributed to subscribers through email