Understanding the State Hook

React introduced Hooks to manage state and other React features in functional components. In this article, we’ll explore the concept of State Hooks by using our playing card component that utilises a state hook to manage the colour of its suit.

What is a State Hook?

A state hook in React refers to the useState or useReducer hooks which are built-in functions that allow functional components to have state variables. It enables the management of state within functional components, providing a way to store and update data that can trigger the re-rendering of the component when the state changes.

In this article, I will discuss useState only.

The useState function signature

The signature of the useState hook looks like this:

const [state, setState] = useState(initialState);
  • state is the variable that will hold your state value
  • setState is the function that will be executed to update your state variable
  • initialState can be thought of as the default value for your state variable

With this in mind, let’s look at how the playing card makes use of useState as an example.

A useState Example

In our playing card component, an example of useState manages the state of the suit colour.

import { useState } from 'react';

const [suitColor, setSuitColor] = useState("red");

To update the value of suitColor, setSuitColor can be called with a string value as a parameter. You can see this happening before the return statement in our component:

setSuitColor("black")

Hence, this will set the playing card’s colour for the next render.

Conclusion

This is just a short side note to show how we use state in the playing card component. Once the application progresses, we must implement state management in more places. Thanks for reading! Don’t forget to check out all of my other React articles here!

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments