In class components, React provides us a built-in state object which is used to store data of that particular component. When the state changes, the component automatically re-renders. This state object works only in class components.
React provided us useState hook that can be used to manage the state in functional components as well.
Let’s take an example of a counter application that counts the number of times the button is clicked. First, we will see using state counter in class component.
useState is a hook that lets you use state inside functional components. useState accepts one argument that is the initial state and it returns the current state value and a function that lets you update the state. Calling this function to update the state will cause re-rendering of the component as the state changes. React will preserve this state between re-renders.
State variables can have string, array, boolean, objects or any type. Now we will do the same counter example using useState in the functional component.
To use useState we have to import it from react.
import React, {useState} from 'react';
At first, we have set the initial value of the count to 0. Clicking on the button will call buttonclick method that will set the count value to count+1 using the setCount method.
Declaring multiple state variables at once
useState allows us to declare only one state variable of any type at once. To use multiple states in a component we can use the state hook for each state. For example:
const [name, setName] = useState("") const [age, setAge] = useState(30)
State variables can hold objects and arrays so we can group related data together.
State Mutation
Let’s take an example of using the object as a state variable.
When we type in the text box to update message, id gets removed. useState does not automatically merge state like this.state in class components. It makes useState different from this.state in class component. When using useState we can use the spread operator to merge the previous state with the new state. For example :
In the above example, we have used a callback function to get the prevState and then using the spread operator merged the prevState with the new state.
Subscribe to our Youtube channel for more videos :