How to use useState hooks in React?

How to use useState hooks in React?

Learn React useState Hook step by step

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

In this article, I will walk you through how the useState hook works in React.

useState

In this example, we are rendering a counter. Counter's value increases when we click on the button.

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

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

useState is a hook that allows us to have state variables in functional components. We can use the initial state to this function and it returns a variable with the current state value and another function to update this value.

What does the React.useState Hook do?

As I mentioned previously, useState enables you to add state to functional components. When we Call useState inside a function component it generates a single piece of state associated with that component.

Whereas the state in a class component is always an object, with hooks, the state can be any type. State can be an object, an array, a boolean, or any other type you can imagine.

When would we use the useState Hook?

useState is especially useful for local component state. But the problem is we can not use it with larger projects, so this problem requires additional state management solutions.

Declaring state in React

To import useState we can write :

import React, { useState } from 'react';

The useState Hook allows you to declare only one state variable (of any type) at a time, like this:

import React, { useState } from 'react';

const Message= () => {
   const messageState = useState( '' );
   const listState = useState( [] );
}

useState takes the initial value of the state variable as an argument.

The initial value will be assigned only on the initial render.

   const Message= () => {
   const messageState = useState( () => expensiveComputation() );
   /* ... */
}

If we want to update the state based on the new properties the component receives:

const Message= (props) => {
   const messageState = useState( props.message );
   /* ... */
}

But useState doesn’t return just a variable as the previous examples imply.


So, hope this article will help you understanding how useState can be used.

Thank You for Reading..!! 😀

Happy To connect at

LinkedIn | Twitter | Github