React JS

How to Manage State in React with the useState Hook

How to Manage State in React with the useState Hook

Manage State in React

What is State in React?
The state is a React Component instance. A class can be described as an object with a number of observable properties that regulate how a component behaves. In other words, a component's state is an object that contains data that could change throughout the course of the component's existence.

useState hook
React's useState hook allows us to manage state. For employing the useState hook, import React Library

Call useState like you would any other function, passing it our whole array of to-dos as initial input.

Using useState, two members of an array are returned:
1. Our state variable is created from the initial value we obtained by calling useState with (our array of to-dos).
2. a unique function that enables updating the data in the state variable

const [user, setUser] = useState({
  username: "",
  permissions: [],

const login = (user) => {
  if (user === "admin") {
      setUser({ username: user, permissions: ["view_extra"] });
  } else {
      setUser({ username: user, permissions: ["view_about"] });
  navigate(redirectPath, { replace: true });

What happens when useState is called?
There is a "state variable" declared. username is the name of our variable, but it might also be called anything else. This allows for the "preservation" of some values in-between function calls; useState is a brand-new approach to access the same functionality that this.state offers in a class. Variables often "disappear" after the function ends, but React preserves state variables.

Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.