/  Technology   /  UseState Hook in React JS

UseState Hook in React JS

 

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. React hooks are an updated and easier approach to using react life cycle methods. Hooks allow function components to have access to state and other React features. Because of this, class components are generally no longer needed.

useState hook is the most commonly used hook in react.

useState

This hook is a state management hook that allows you to store and manipulate date or state stored in it. This hook takes in two parameters i.e state and setState. Giving the setState is  mandatory and must be given in camel casing only. The hooks in react are syntactically strict.

Syntax

const [ state, setState] = useState()

Hook Rules :

  • Hooks can only be called inside React functional components.
  • Hooks can only be called at the top level of a component.
  • Hooks cannot be conditional

useState Example

import React, { useState } from "react";
import ReactDOM from "react-dom/client";
function FavoriteColor() {
  const [color, setColor] = useState("red");
  return (
    <>
      <h1>My favorite color is {color}!</h1>
      <button
        type="button"
        onClick={() => setColor("blue")}
      >Blue</button>
     </>
  );
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);

Before using the useState we are required to import it from the react library like shown above. In the code we are making the use of useState hook to manipulate the stored color. 

Here we have created a button which onClick calls a function FavoriteColor(), this function is storing the state and setState. We can pass multiple values in the parameter of useSate(), it considers it as the initial value. Thus, here we have given the color name ‘red’ as the initial value. 

In the jsx we are displaying the stored value dynamically using the state name in flower brackets {}. And on the button onClick event we are setting the state i.e using setState to update or modify the initial value. Therefore, wheneve the button is clicked the state value changes and is displays “My Favorite color is blue”.

Output :

  UseState Hook in React JS

 

Leave a comment