☰ See All Chapters |
React useState hook to access state
The state is a built-in React object that is used to contain data or information that belongs to the component. When this state object changes, React re-renders the component to the browser. The change in state can happen as a response to user action or system-generated events and these changes determine the behavior of the component and how it will render. Using the useState() API, you can create a new state variable, and have a way to alter it.
Import useState
To use the useState Hook, we first need to import it into our component.
import { useState } from "react"; |
Initialize useState
useState() accepts the initial value of the state item and returns an array containing the state variable, and the function you call to alter the state variable. Since it returns an array we use array destructuring to access each individual item, like this: const [count, setCount] = useState(0)
import { useState } from "react";
function DemoComponent() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }
export default DemoComponent; |
You can add as many useState() calls you want, to create as many state variables as you want. Just make sure you call it in the top level of a component (not in an if or in any other block).
import { useState } from "react";
function DemoComponent() { const [firstName, setFirstName] = useState("Manu"); const [lastName, setLastNAme] = useState("Manjunatha"); const [gender, setGender] = useState("Male"); return ( <> <h1>First Name: {firstName}</h1> <h1>Last Name: {lastName}</h1> <h1>Gender: {gender}</h1> </> ); }
export default DemoComponent; |
It is not necessary to define function to alter the state variable. You can just ignore or useState() can returns an array containing only state variable.
import { useState } from "react";
function DemoComponent() { const [firstName] = useState("Manu"); const [lastName] = useState("Manjunatha"); const [gender] = useState("Male"); return ( <> <h1>First Name: {firstName}</h1> <h1>Last Name: {lastName}</h1> <h1>Gender: {gender}</h1> </> ); }
export default DemoComponent; |
Or, we can just use one state and include an object instead!
import { useState } from "react";
function DemoComponent() { const [employee, setEmployee] = useState({ firstName: "Manu", lastName: "Manjunatha", gender: "Male" }); return ( <> <h1>First Name: {employee.firstName}</h1> <h1>Last Name: {employee.lastName}</h1> <h1>Gender: {employee.gender}</h1> </> ); }
export default DemoComponent; |
Updating Objects and Arrays in State
When state is updated, the entire state gets overwritten. What if we only want to update only a particular variable from state? If we only called setEmployee({lastName: "M"}), this would remove the firstName and gender from our state. We can use the JavaScript spread operator to help us.
demo.component.js
import { useState } from "react";
function DemoComponent() { const [employee, setEmployee] = useState({ firstName: "Manu", lastName: "Manjunatha", gender: "Male" });
const updateEmployee = () => { setEmployee(previousState => { return { ...previousState, lastName: "M" } }); } return ( <> <h1>First Name: {employee.firstName}</h1> <h1>Last Name: {employee.lastName}</h1> <h1>Gender: {employee.gender}</h1>
<button type="button" onClick={updateEmployee} >Update Last Name</button> </> ); }
export default DemoComponent; |
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import DemoComponent from './components/demo.component'; import reportWebVitals from './reportWebVitals';
ReactDOM.render( <React.StrictMode> <DemoComponent firstName = "Manu" lastName="Manjunatha"></DemoComponent> </React.StrictMode>, document.getElementById('root') );
reportWebVitals(); |
All Chapters