Dev.to AI 🤖 Ai 👁 0 📖 1 min read

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 automati

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);

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";

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");
}

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 />
);

Update State

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

<button
  type="button"
  onClick={() => setColor("blue")}
>Blue</button>

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 />
);

Reference

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

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.