DevOps | Cloud | Analytics | Open Source | Programming





How To Use The State Hook (useState) in React.js ?



In this post, we will explore - How To Use The State Hook in React.js. State management in React involves tracking how data changes within an application There are various methods of managing state, including class-based state management and third-party libraries like Redux Hooks is a method of state management in React that allows developers to write shorter, more readable code without using classes

  • The useState and useReducer Hooks are used to set state in functional components
  • The useState Hook is useful for setting a value without referencing the current state
  • The useReducer Hook is useful for referencing previous values or when complex data manipulation is needed
 

1. Set-Up :

  • A development environment with Node.js is required.
  • Preferably use the latest Node.js version & npm version
 

2. Basics of Hooks :

  • Hooks are a new feature in React 16.8 that allow developers to use state and other React features without writing a class
  • Hooks can be used inside function components, which were previously known as "stateless components"
  • Hooks are special functions that allow developers to "hook into" React features, such as the useState Hook, which allows developers to add state to function components
  • Hooks can be used to avoid the need to convert a function component to a class when adding state
  • The useState Hook lets developers add state to function components by providing the current state and a function to update the state
 

3. Declaration of State Variable :

  • In a class, state is initialized in the constructor
  • In a function component, the useState Hook is called to declare a state variable
  • Calling useState creates a state variable that preserves values between function calls, similar to this.state in a class
  • The state variable can be named anything, and is initialized with a value passed to the useState Hook
  Let's first study a class based example -


class Example extends React.Component {
  constructor(props) {
   super(props);
   this.state = { count: 0 
   }; 
}

  • The above code defines a class called Example that extends the base React.Component class.
  • The class has a constructor function. The constructor function is used to initialize the state of the class.
  • Here the constructor function initializes the state by setting the count property to 0.
  • The count property is stored in this.state, which is a special object that holds the state of the component.
  • The state is used to store data that can change within the component, and it can be accessed and updated using the this.state object.
  • The super(props) call is used to call the constructor function of the base class (React.Component). This is required in the constructor function of any class that extends another class.
  • Overall, this code defines a class-based component in React that has a state with a count property that is initialized to 0. When the component is rendered, it will display the current value of the count property. The count property can be updated by modifying this.state
  Now we move from the class-based example to hook example as below -


import React, { useState } from 'react';

function Example() {
 // Declare a new state variable - "count" 
 const \[count, setCount\] = useState(0);
}

  • This code imports the useState Hook from the react module and defines a function component called Example.
  • Within Example function, the useState Hook is called to declare a new state variable called count.
  • The useState Hook takes a single argument, which is the initial value of the state variable.
  • In this case, the initial value is 0.
  • The useState Hook returns an array with two elements: the current value of the state variable and a function to update the value.
  • These two elements are destructured and assigned to the variables count and setCount, respectively.
  • The count variable holds the current value of the state variable, which is initially set to 0.
  • The setCount function can be called to update the value of the state variable. When the state variable is updated, the component will be re-rendered to reflect the change.
  • Overall, this code defines a function component in React that has a state variable called count that is initialized to 0. The component can be rendered with the current value of count, and the count variable can be updated by calling the setCount function.
   

4. Calling a useState Variable :

  • Calling the useState Hook creates a state variable in a function component.
  • The state variable is a way to "preserve" values between function calls, similar to the way that this.state works in a class-based component.
  • The state variable is initialized with a value passed to the useState Hook as an argument.
  • The initial value can be any type, such as a number, string, object, or array.
  • The useState Hook returns an array with two elements: the current value of the state variable and a function to update the value.
  • The current value is stored in a variable that is declared when the useState Hook is called, and the update function is stored in a separate variable.
  • The state variable and update function can be named anything, and are usually given descriptive names that reflect the purpose of the state variable.
  • In the above example, the state variable is count and the update function is called setCount.
  • When the state variable is updated, the component will be re-rendered to reflect the change.
  • This allows the component to be dynamic and responsive to user input or other events.
  • Overall, calling the useState Hook is a way to create and manage state in a function component, allowing the component to be dynamic and responsive to changes.
 

5. Passing Arguments to useState :

  • The useState Hook is called with a single argument, which is the initial value of the state variable. The initial value can be any type, such as a number, string, object, or array.
  • In the example given, the initial value is 0, which is passed as an argument to the useState Hook. This initializes the state variable called count to 0.
  • The useState Hook returns an array with two elements: the current value of the state variable and a function to update the value.
  • The current value is stored in a variable that is declared when the useState Hook is called, and the update function is stored in a separate variable.
  • If you need to store multiple values in state, you can call the useState Hook multiple times, each with a different initial value.
  • For example, if you need to store both a number and a string in state, you could call useState twice, like this:

const \[count, setCount\] = useState(0); 
const \[name, setName\] = useState("");

  • Overall, the useState Hook is called with a single argument, which is the initial value of the state variable. This initializes the state variable and provides a way to update it when needed.
 

6. Returning Something From useState :

  • The useState Hook returns a pair of values: the current state and a function to update the state.
  • The current state is stored in a variable that is declared when the useState Hook is called, and the update function is stored in a separate variable.
  • In the example given, the useState Hook is called with an initial value of 0, which initializes the state variable called count to 0.
  • The useState Hook returns an array with two elements: the current value of count and a function called setCount to update the value of count.
  • The current value of count is stored in the count variable, and the setCount function can be called to update the value of count.
  • When the value of count is updated, the component will be re-rendered to reflect the change.
  • The useState Hook is similar to this.state.count and this.setState in a class-based component, except that the current state and update function are returned in a pair.
  • Overall, the useState Hook is used to create and manage state in a function component, allowing the component to be dynamic and responsive to changes.
  • The current state is stored in a variable, and a function is provided to update the state when needed.
 

7. Reading State :

Class-Based :

  • In a class-based component, the state is stored in the this.state object, and the current value of a state variable can be accessed using this.state.variableName.
  • For example, to display the current count in a class-based component, you would use this.state.count:
 


class Example extends React.Component { 
// ... 
render() { 
   return ( 
       <div> <p>You clicked {this.state.count} times</p> 
       <button onClick={() => this.setState({ count: this.state.count + 1 })}> 
          Click me 
       </button> 
       </div> 
       ); 
  } 
}

 

Function-Based :

  • In a function component, the state is stored in variables that are declared using the useState Hook
  • The current value of a state variable can be accessed using the variable name.
  • For example, to display the current count in a function component, you would use the count variable directly:

import React, { useState } from 'react';

function Example() { 
  const \[count, setCount\] = useState(0); 
  return ( 
    <div> 
      <p>You clicked {count} times</p> 
      <button onClick={() => setCount(count + 1)}> Click me </button> 
    </div> 
   ); 
}

 

8. Updating State :

Class-Based :

  • In a class-based component, the state is stored in the this.state object and the setState function is used to update the state.
  • The setState function takes an object as an argument, which contains the updated values for the state variables.
  • For example, to update the count state in a class-based component, you would call the setState function and pass an object with the updated value for count:
 


class Example extends React.Component { 
// ... render() { 
  return ( 
    <div> 
       <p>You clicked {this.state.count} times</p> 
       <button onClick={() => **this.setState({ count: this.state.count + 1 })**}> Click me </button> 
    </div> 
  ); 
 } 
}

 

Function-Based :

  • In a function component, the state is stored in variables that are declared using the useState Hook, and the update function is used to update the state.
  • The update function takes a single argument, which is the new value for the state variable.
  • For example, to update the count state in a function component, you would call the update function and pass the new value for count:
 


<button onClick={() => **setCount(count + 1)**}> Click me
</button>

 

9. Using Multiple useState :

  • Declaring multiple state variables using the useState hook in React allows you to give different names to different state variables
  • That can be useful for organizing your state management in a more intuitive way.
  • The useState hook returns an array with two elements: the current value of the state variable, and a function that can be used to update the value of the state variable.
  • While you can use multiple state variables to manage different pieces of state separately, you can also use a single state variable to store an object or array that contains related data.
  • However, it's important to note that when you update a state variable using the function returned by the useState hook, the entire state variable is replaced, rather than being merged with the existing state like setState in a class component does.
  Let's understand the below code -

  • The ExampleWithManyStates function is a React component that uses the useState hook to declare three state variables: age, fruit, and todos.
  • The useState hook returns an array with two elements: the current value of the state variable, and a function that can be used to update the value of the state variable.
  • The component has a function called handleOrangeClick that updates the value of the fruit state variable to 'orange' when it is called.
  • This is done by calling the setFruit function that was returned by the useState hook when the fruit state variable was declared.
  • It's worth noting that when you update a state variable using the function returned by the useState hook, the component will re-render and the new value of the state variable will be reflected in the component's UI.
 


function ExampleWithManyStates() {
   // Declare multiple state variables
   const \[age, setAge\] = useState(42);
   const \[fruit, setFruit\] = useState('banana');
   const \[todos, setTodos\] = useState(\[{ text: 'Learn Hooks' }\]);


function handleOrangeClick() {
  // Similar to this.setState({ fruit: 'orange' })
  setFruit('orange');
}

 

10. Alternative to useState :

  • The useReducer hook in React is a way to manage state that is an alternative to the useState hook.
  • It is often used for more complex state logic that involves multiple sub-values or when the state depends on previous values.
  • To use the useReducer hook, you first need to define a reducer function that takes in the current state and an action, and returns the updated state.
  • Then, you can call the useReducer hook, passing in the reducer function and an initial state value as arguments.
  • The useReducer hook returns an array containing the current state value and a dispatch function.
  • To update the state using the useReducer hook, you call the dispatch function and pass it an action object.
  • An action object typically has a type property that specifies the type of action being taken, and may also have a payload property that provides additional information needed to update the state.
    Hope this helps you to understand Use The State Hook (useState) in React.js.  

Additional Posts you might want to read from this Blog -

   


what is hooks in react ,usestate in react js ,useeffect hook ,react-use ,react custom hooks ,how to use the state hook in react js ,How does React state hook work? ,What is state hook in React? ,How do you call a function in useState hook? ,How do you use setState in React? ,useeffect react ,usestate in react w3schools ,react hooks ,react usestate array ,usestate vs useeffect ,usestate in react native ,usestate object ,useeffect in react js ,hooks in react js ,React ,useState hook ,state in function component ,state management ,function component ,useState hook in React ,useState hook example ,initial state ,update state ,state variables ,useState hook explained ,state in React ,useState hook array ,useState hook tutorial ,state management in React ,useState hook with function component ,useState hook in function component ,React state management ,state in function component with useState hook