Published on

React & useState() Hook

Authors
  • avatar
    Name
    Kieran Hauser
    Twitter

How React's useState() Hook Works

React's useState() hook is a powerful tool that allows developers to manage state within functional components. The hook takes an initial state value as an argument and returns an array with two elements: the current state value and a function to update that value.

Here's the syntax for useState():

const [state, setState] = useState(initialState);

In the above code, state represents the current state value, and setState is a function that allows us to update the state. We can call setState with a new state value, and React will re-render the component with the updated state.

Now, let's see how we can use useState() to build a card game in React.

Example: A Card Game Using useState()

Suppose we want to build a simple card game where the user can click on a card to reveal its value. We can represent the game state as an array of card values and use useState() to manage the state.

Here's how the code might look:

mport React, { useState } from 'react';

function CardGame() {
  const [cards, setCards] = useState(['A', 'K', 'Q', 'J']);

  function handleClick(index) {
    const newCards = [...cards];
    newCards[index] = 'X';
    setCards(newCards);
  }

  return (
    <div>
      {cards.map((card, index) => (
        <div key={index} onClick={() => handleClick(index)}>
          {card}
        </div>
      ))}
    </div>
  );
}

In this example, we start with an array of cards with values ['A', 'K', 'Q', 'J']. We render each card as a <div> element and attach an onClick handler to it. When the user clicks on a card, we update the state by creating a new array with the clicked card replaced by the value 'X'. We then call setCards() to update the state and trigger a re-render.

As you can see, useState() allows us to easily manage state in a functional component and build complex UIs with ease. With a little bit of creativity, you can use useState() to build all sorts of interesting applications in React.