DEV Community

SavvyShivam
SavvyShivam

Posted on

useState in React

What is a State?

The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. For example, let us think of the clock that we created in this article, we were calling the render() method every second explicitly, but React provides a better way to achieve the same result and that is by using State, storing the value of time as a member of the component’s state.

useState is a React Hook that lets you add a state variable to your component.

How to import useState?

To add a state variable, import useState from React at the top of the file.

Adding State to a component

We use the following convention to name the state variables:
const[something, setSomething] = useState(initial state)

This is referred to as array destructuring.
Here :

  1. Count represents the current state of the state variable. It initially takes the initial state that is provided in the useState.

  2. setCount represents the function that changes the state.

The following code gives an example of how the set function works. We call the state function and update it with the next state.

Here, the initial state of the count was zero. By creating a function “incrementing” we update the state of the state variable and set the count as count+1.

Rendering a State:

A change in state triggers a render. Rendering takes place in the following ways:

  1. Reacts calls the component

  2. In the initial render, React calls the root component.

  3. After the initial render, for the subsequent renders, React calls the function component that resulted in a state change/update which triggered the render.

The same happens in the decrementing function.

Everytime the button named decrement will be clicked, the counter will decrease by 1.

Lastly in the return, we create two buttons and associate the onClick event handler with the state functions.

Output

The link to the entire code is given below. Check it out!
https://codesandbox.io/s/counter-state-wkote0

Top comments (0)