DEV Community

Cover image for Usestate in React
Kamalesh AR
Kamalesh AR

Posted on

Usestate in React

Usestate

The React useState Hook allows us to track state in a function component.
useState is a React Hook that allows functional components to store and update data (state). Whenever the state changes, React automatically re-renders the component to display the updated UI.

Syntax

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

state - The current value.
setState - Function used to update the state.
initialValue - The initial value of the state.

Import useState

To use the useState Hook, we first need to import it into our component.

import { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

Notice that we are destructuring useState from react as it is a named export.

Initialize usestate

We initialize our state by calling useState in our function component.

useState accepts an initial state and returns two values:

The current state.
A function that updates the state.

import { useState } from "react";

function FavoriteColor() {
  const [color, setColor] = useState("red");
}
Enter fullscreen mode Exit fullscreen mode

Notice that again, we are destructuring the returned values from useState.

The first value, color, is our current state.

The second value, setColor, is the function that is used to update our state.

Lastly, we set the initial state to "red": useState("red")

Read State

We can now include our state anywhere in our component

import { useState } from 'react';
import { createRoot } from 'react-dom/client';

function FavoriteColor() {
  const [color, setColor] = useState("red");

  return <h1>My favorite color is {color}!</h1>
}

createRoot(document.getElementById('root')).render(
  <FavoriteColor />
);
Enter fullscreen mode Exit fullscreen mode

Update State

To update our state, we use our state updater function.

<button
  type="button"
  onClick={() => setColor("blue")}
>Blue</button>
Enter fullscreen mode Exit fullscreen mode

EXample

import { useState } from 'react';
import { createRoot } 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>
    </>
  )
}

createRoot(document.getElementById('root')).render(
  <FavoriteColor />
);
Enter fullscreen mode Exit fullscreen mode

Reference

https://www.w3schools.com/react/react_usestate.asp

Top comments (0)