Introduction

Hello! Today, we will be unlocking our mastery over states in React.js. Imagine a weather app tracking the changing weather—that's a state in React.js.

Understanding States in React.js

A state in React.js is like a component's memory. It's data stored by a component that can change over time in response to user actions or other events. Consider a game app where your score (state) starts at 0 and increases by 1 with each point:

import { useState } from 'react';

// ScoreCounter Component
function ScoreCounter() {
  // Score counter starts from 0
  const [score, setScore] = useState(0);

  return (
    <div>
      {/* displaying the score */}
      <p>Your score: {score}</p>
      {/* onclick of 'Score' button, 
          the score will increase by one */}
      <button onClick={() => setScore(score + 1)}> Score!</button>
    </div>
  );
}

export default ScoreCounter;

The score is our state, and we use setScore to update it. In the code above, the setScore function increases the score each time the Score button is clicked.

Introducing useState Hook

Now, let's look closer at the useState hook. React hooks allow us to use React features within functional components. The useState hook enables us to create state variables. Consider the following snippet:

const [score, setScore] = useState(0);

useState(0) initializes our state variable score to 0. It's our initial state. In an online game, each player's initial score would be 0.

This useState hook returns an array with two entries: the current state (score) and a function to update it (setScore). We're using JavaScript's array destructuring to assign names to them. The setScore function lets us change the current score.

Using useState Hook with Various Event Listeners

We can harness the useState hook with different types of event listeners to create more interactive components. Let's look at an example where the color of a div box changes every time a mouse hovers over it:

import { useState } from 'react';

function ColorChanger() {
  const [color, setColor] = useState('red');

  return (
    <div 
      style={{ backgroundColor: color, height: '200px', width: '200px'}}
      onMouseOver={() => setColor('blue')}
      onMouseOut={() => setColor('red')}>
    </div>
  );
}

export default ColorChanger;

In this code, when the mouse hovers over the div (onMouseOver), the background color changes to blue, and it returns to red when the mouse pointer is moved away (onMouseOut).

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