State in React
State in React corresponds to changing the contents displayed to the user. This could occur because of multiple factors, such as in response to user interaction or some internal changes to the data in the application.
Such changes can be managed in React by using the concept of State. Unlike normal React variables, a change of the state in React triggers the re-execution of the Component function. This corresponds to re-rendering.
We can define the state in React using the useState hook. Hooks in React are used to implement various functionality in React.
Steps to Define State in React
1. Import the useState hook from the React library.
import {useState} from 'react';
2. Define the state in the component function by calling the useState function.
This sets the initial value of the state variable of ''
useState('');
useState function returns an array with two values. The first value is the state variable, the and second value is the state setter function. So to update the state we need to use this setter function. We can not assign the value to the state variable directly. Assigning value to the state using the setter function signals to React that it should re-render the component. Since React updates the DOM elements through conditional rendering so the setState function causes React to perform conditional re-render.
const [name,setName]=useState('');
We now set the value of the name by calling the state-updating setName function.
setName('User1');
This call assigns the new value to the name state and also updates the screen to reflect the state changes.
We can assign new values on some particular even, such as the button click as.
<button onClick={()={useState('User2');}} className="button">Add book</button>
The state defined using the useState hook is specific to the specific component instance.
Updating Object property
For updating the object property value with a new value, you should use the spread JS syntax. In this example, we are just updating the firstName property.
setEmployee({
...employee,
firstName: e.target.value
});
Accessing Previous State value
If you need to update the previous state value with the new one, you should use the previous state parameter. For example, in this example, we are accessing the isAllowed parameter and updating it based on the previous value.
this.setState(previousState => {
return {
isAllowed: !previousState.isAllowed
}
})