React hooks useState example
React hooks are the latest features introduced in functional classes to limit class component uses.
React supports two types of component types.
- Functional components: these are functions with arguments and return JSX (mix of javascript and HTML) code and there is no state management before react V0.16.7 version, also called stateless components.
- Class components: these are stateful components, contain state, lifecycle methods, these are created by extending the
React.Component
class.
Several hooks are introduced in react latest versions. useState
is a built-in hook introduced in React to update state objects in Functional components.
useState in React functional components
useState abbreviated as use state management in functional components.
In functional components, Storing a local state of a component using useState hook.
A state can be of any type- array, object, boolean, number and string, etc. useState holds only a single type of data.
First, import useState in component
import React, { useState } from "react";
Syntax:
const [variable, setFunction] = useState(defaultValue);
variable
is a new state variable assigned with a default value. setFunction
is a function to update the state variable.
useState
feature
- It can be used in functional components or stateless components
- The state of a component can be managed with this
- It always returns an initial value and a function to update a
- Hooks are not used in react classes
Example, Adding state to functional components
Let’s see an example to increment value in React class components with a button click
In react class components,
- State stores as an object that means can store different types of data (Boolean, array)
import React, { Component } from "react";
class IncrementCounter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCounter() {
this.setState((previous) => ({ count: previous.count + 1 }));
}
render() {
const { count } = this.state;
return (
<div>
<p>Incremented to {count}</p>
<input
type="button"
name="countr"
value="Increment"
onClick={(e) => this.incrementCounter(e)}
/>
</div>
);
}
}
export default IncrementCounter;
useState in React functional components
The above can be rewritten using useState hook with functional components.
import React, { useState } from "react";
function IncrementCounterHook(props) {
const [counter, setCounter] = useState(0);
return (
<div>
<div>Incremented to {counter}</div>
<input
type="button"
name="countr"
value="Increment"
onClick={() => setCounter(counter + 1)}
/>
</div>
);
}
export default IncrementCounterHook;
Let’s see a few examples to update state objects.
What is the difference between the state in functional components and class components?
useState hook update array in functional component
This example explains storing or update an array in the array component. below code, submitting the form with input name and added to state array with functional component
- useState is defined with the initial state as []
- It returns state variable employees of array type and a method setEmployee to update an array.
- addEmployee is called on button click handler
- setEmployees copy the existing employee’s array and add the new value to it.
- spread operator … is used to add new employees to employees.
- Finally displays the state array using the array map function
import React, { useState } from "react";
function HookArray(props) {
const [employees, setEmployees] = useState([]);
const [name, setName] = useState("");
const addEmployee = (event) => {
event.preventDefault();
setEmployees([
...employees,
{
name: name,
},
]);
setName("");
};
return (
<div>
<>
<form onSubmit={addEmployee}>
<label>
Name
<input
name="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<button name="Add" value="Add">
Add
</button>
</form>
<ul>
{employees.map((emp) => (
<li key={emp.empid}>{emp.name}</li>
))}
</ul>
</>
</div>
);
}
export default HookArray;