Lesson Introduction & Goal Setting

Hello, dear learner! Are you ready to delve into the world of React? Today, we'll explore the React state — data that a component manages and modifies. Think of a traffic light: its color (red, yellow, or green) is the state of the traffic light.

Our chief aim is to learn how to utilize useState and setState to manage the state in React components using hardcoded data. Excited? Let's begin!

Understanding What State Is in React

In React, "state" refers to the data of a component that can be monitored and altered. Picture a simple counter: the count value is our state data. When someone clicks the increment button, the count changes, which triggers a re-render.

import React, { useState } from 'react';

function Counter()  {
  const [count, setCount] = useState(0); // Declare 'count' state variable with initial value 0 

  return (
    <div>
      <p>You clicked {count} times</p> {/* Display the current count */}
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button> // Increment count when button is clicked
    </div>
  );
}

export default Counter;

In this code snippet, our state variable count is declared and initialized with 0 using useState(0). When the button is clicked, the count increases, initiating a re-render of the component.

Introducing `useState`

useState is a React hook that introduces state to functional components. useState is used to declare a state variable. It returns a pair: the current state value and a function to update it.

const [myState, setMyState] = useState(initialState);

Let's declare a state variable color with an initial state:

import React, { useState } from 'react';

function ColorChanger() {
  const [color, setColor] = useState("red"); // Declare 'color' state variable with initial value 'red'

  return (
    <div>
      <h1>The current color is {color}</h1> {/* Output the color */}
    </div>
  );
}

export default ColorChanger;
Using `useState` with Hardcoded Data

Suppose we have a favoriteColor component that uses useState to manage hardcoded data:

import React, { useState } from 'react';

function FavoriteColor() {
  const [favoriteColor, setFavoriteColor] = useState("blue"); // Define 'favoriteColor' with initial (hardcoded) value 'blue'

  return (
    <div>
      <h1>My favorite color is {favoriteColor}</h1> {/* Output the favorite color */}
    </div>
  );
}

export default FavoriteColor;

FavoriteColor always displays "My favorite color is blue" — because favoriteColor is hardcoded as "blue".

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal