logo

,

React Hooks: Understanding React UseState and Their Use Cases

You can be sure to have the most productive web development session with React Hooks. The UseState React Hook is one that you will use quite often. Interestingly, this function will make coding fun and easy when trying to reuse elements or update states in your React application.

On the other hand, one of the most effective JavaScript frameworks for developing responsive websites is React.js. If you want to create interactive websites or simple user interfaces for data visualization, SaaS applications, or innovative mobile applications, React is a top tool.

So in this article, you will be learning about the React UseState, one of the popular React Hooks.

What is React UseState?

The useState hook allows you to change and set the state of React components. When you need a reactive value that might change at some point, UseState is the function to use. Hence, to set a new state and keep the old state, you must pass two elements to the useState function.

React preserves state variables, whereas variables typically “disappear” when the function ends.

What is a State in React?

A state in React is merely an internal React object that houses data or details about the component. Additionally, the state may change over time depending on the information in the component, and each time it does, the component re-renders.

The “state” of a React component can be thought of as its “core.” And this controls how that component value renders and behaves; it enables you to create dynamic, interactive components.

Therefore, when we refer to a component’s state, the data is being used by that component. This state could be objects, strings, or countless other values.

How Does the UseState Work?

Let’s use a simple illustration, which we will represent later in an example, to explain how the UseState works.

Let’s say you create some variables in a component and plan to implement changes to this variable over time. We now know that React components do not reload to welcome changes based on how they update on the web. But what if we had variables or data that we wanted to change in response to an event, like a user clicking a button?

Without the React UseState, when we update the function with a new variable to replace the initial value, it will not update. For better comprehension, let’s use an example to illustrate this situation.

  • Open your VSC, open your terminal and enter
npx create-react-app my-app

Create a new file to contain our code under the src folder

Code example

const CrFm = () => {
  // initialize the original state value.
  let PlayerName = "C.Ronaldo";

  // When the button is clicked, we'll attempt to change the 
  //original player name value in the function.

  const hanClik = () => {
    PlayerName = "L.Messi";
    // This is to check if our changes worked
    // use fn+f12 on your browser to view the console output.
    console.log(PlayerName);
  };

  <div>
    <h3> Who is the best player in the world? </h3>
    <h4>
      <i>{PlayerName}</i>
    </h4>

    /* button to change the event(Player name) */
    <button onClick={hanClik}>Click to See The Next Best Player</button>
  </div>;
};  

export default CrFm;

Import the code into your app file

import "./App.css";
import Cm from "./CrFm";

function App() {
  console.log("working");

  return (
    <div>
      <Cm />
    </div>
  );
}

export default App;
  • Enter the following on your terminal to test the code above:
    • cd my-app
    • npm start

As you can see from the display in the example above, the component does not update on the web, but it does update on the console. Therefore, we need the React UseState to have these changes on the component.

How to Use the React UseState to Update State Components

From the example above, you may have noticed the component’s refusal to acknowledge the change made. This explains the effect of React UseState when we say you use it to hold and update the state of a component in React.

To demonstrate how the UseState addresses the issue in the example in the other section, we will use the example from above. Therefore, using a state hook allows for the creation of reactive values and changing them whenever we want.

Therefore, we must import the UseState hook at the top of the file before using it. Destructuring the UseState hook with curly braces will allow us to use it inside our component.

#Example

// code to import useState hook
import { useState } from "react";

const CrFm = () => {
  // initialize the original state value using the useState this time
  // use array destructuring to grab the values
  const [PlayerName, setPlayerName] = useState("C.Ronaldo.....");

  // When the button is clicked, we'll attempt to change the original player name value in the function.
  const hanClik = () => {
    // Since we are using the UseState function, you can use the setPlayerNmae to change the value.

    setPlayerName("L.Messi.....");
  };

  return (
    <div classname="chrome">
      <h1>Learn How UseState Works</h1> <br></br>
      /* This is where the player name outputs */
      <h3> Who is the best Player in the World?</h3>
      <h4>
        <i>{PlayerName}</i>
      </h4>
      /* button to change the event(Player name) */
      <button onClick={hanClik}>Click to See The Next Best Player</button>
    </div>
  );
};

export default CrFm;

Remember to import the CrFm module into your app file.

import "./App.css";
import Cm from "./CrFm";

function App() {
  console.log("working");

  return (
    <div>
      <Cm />
    </div>
  );
}

export default App;

#Below is the OUTPUT before clicking the button

#Below is the OUTPUT after clicking the button

Uses of React UseState Hook

The useState hook is a unique function that accepts the initial state as an argument and outputs an array with two elements. In addition to the function to update the state, it returns the current state. When designing forms and other components that need inputs or that need to be updated based on the outputs of other components, the useState feature is helpful.

Additionally, you can use multiple state variables. UseState tells React that you want this component to remember or keep track of a value.

The official React documentation lists just two rules for the useState hook.

  • React hooks typically don’t work in non-functional components, so the useState hook can only be used in functional components.
  • Always use the useState hook at the top of your React functional component before returning any JSX.

Conclusion

UseState allows you to incorporate the local state into a functional component. You can use this function to include state variables in functional components.

Don’t forget to checkout: Understanding React Forms, and How to Create a Form in React

Don’t forget to checkout: Complete React Developer (w/ Redux, Hooks, GraphQL)


Share on facebook
Share on twitter
Share on linkedin

Related articles