In this React js tutorial, we will learn about the State in React js Hooks. And also we will discuss the below points:
- What are Hooks in React js?
- State in react js functional component
- state management in react js
- usestate in react js
- global state in react js
- dynamic state react js
- react js state and lifecycle
- react js update state from another component
What are Hooks in React js?
Hook gets added to the React in the 16.8 version. Hook allows React functional components to have entry to state and other react features. Therefore class components are no longer needed, which means hooks in React replace the class component.
Example of Hooks useState()
import React, { useState } from 'react';
function PersonName() {
const [name,setName] = useState('Alex');
return (
<h1>Welcome to {name}</h1> //Return Alex
);
}

State in react js functional component
Here we will see how to define State functionality with Hooks in React js functional component.
So here we will see a Counter example, which gets incremented every time, the button gets clicked.
The Index.js file is the starting point of the React app, so it contains the below code.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
Then in App.js file contains the below set of code:
import './App.css';
import Counter from './Components/Counter';
function App() {
return (
<div className="App">
<Counter></Counter>
</div>
);
}
export default App;
Next, the Counter.js file contains the below set of codes, that will increment the counter default value ‘0’ by 1.
import React, { useState } from 'react';
function Counter() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<h1>To increment the counter by 1, click on button.</h1>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;
Now run the React app with the npm start command and you can see the counter is set to 0 if you need to increment by 1.

Read Setup React js environment and Create your first react app with react js
State management in react js
Here we will see how we can manage state in our React application. The React is not enough to handle the large application complexity, so developers use different types of state management libraries like Hooks, Redux, and many more.
What is State Management in React js?
React component comes with a built-in state object, this state is nothing but encapsulated data where we can store data, that is constant between component rendering.
In Javascript data structure, the state is just a fancy term, if the user changes the state in the React app, the User Interface looks completely different, because the application is defined with the new state rather than an old state.
Why do we need state management in React js?
Using components, react applications are built and they are managed by the state internally, it works well for React apps with few components but when the applications grow larger the complexity of managing states’ distribution across components becomes challenging.
Let’s take an example of an e-commerce application, in which the status of multiple components will change when buying a product.
- Appending the product to the shopping list
- Assigning product to customer history
- trigger count of the purchased product
For developers, it is really hard to find out what is happening when something goes wrong, if they do not have scalability in mind. That’s why we need state management in our application.
And to manage the state in React application we will use the react hooks.
Four different types of React state to manage
When we talk about state management in the application, it is important to know what kind of state actually matters.
There is four important kinds of React states to manage:
- Local state
- Global state
- Server state
- URL state
Local State
With a Local state, we can manage the data in one component. In React the local state is often managed by the useState hook.
For example, we use local state in React to hide or show modal components, and also we can track data for a form component, such as form submission and the data from form inputs.
The useState hook is perfect to work on a small number of local states in React components. This method call can handle one value and while we make that one value an object that contains a set of other values, so it is better to split them up.
If we call useState 3 to 5 times in a single component, it is difficult to keep track. To level up the useState is useReducer. The reducer function provides us with one centralized place to intercept actions and update the state accordingly. A useReducer call like useState, but with a reducer, it is common for the single value to be an object containing more than one value.
Global state
With global state, we can manage the state across multiple components in React JS. If we want to get and update data from anywhere from your app, with a global state
For example, when a user is login to an application, the global state is authenticated as the user state. As the user logged in, it is important to get and change their data in the whole application.
Server state
From an external server, the data comes must be integrated with the UI state. As server state is a simple concept in React js, but it is harder to manage alongside all of the global and local states.
There are several pieces of state managed in React application, every time we get and update data from an external server, which includes loading and error states also.
URL state
It is the data that is present on URLs, which includes the query parameter and path name. In many cases of our application, a lot of major parts, depend on accessing the URL state.
Read What is JSX in React js
useState in react js
Here we will see an example of how to use useState in react js hook.
The React useState- Hook is used to track the state in the functional component. The data that needs to be tracked in React application is known as the state.
The useState hook takes the initial state as an argument and returns an array of two entries i.e. Current state and a function that updates the state. With useState, we can encapsulate only one value from the state and for multiple states, we need to have useState calls.
Syntax of useState-Hooks in React js
const[state, setState]= useState(initialState)
To use useState in the application we need to import the useState hook.
import React,{useState} from "react"
Example: We will create a component that will render random number on page. Every time we will click on the button, the random number will re-render on the page.
Let’s say index.html contains the below statement inside the body tag:
<div id="root"></div>
Next in the index.js file write the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
Next, the App component is the default component and contains below set of code:
import './App.css';
import UseStateExample from './Components/UseStateExample';
function App() {
return (
<div className="App">
<UseStateExample></UseStateExample>
</div>
);
}
export default App
Now in the UseStateExample component, write the below code.
import React,{useState} from "react"
function UseStateExample(){
const[num,setRandomNum]= useState (function genarateRandomInteger(){
return Math.floor(Math.random()*100);
})
function clickHandle(e){
setRandomNum(Math.floor(Math.random()*100));
}
return(
<div>
<h1>{num}</h1>
<p><button onClick={clickHandle}>Click</button></p>
</div>
);
}
export default UseStateExample
Now run the app using the npm start command, and you can see a random number render on the page then click on the button to see the new number.

This is how we can use useState-Hook in React js.
Read Props in React js
Dynamic state react js
Here we will see how to use useState() and useEffect() hooks to dynamically render components.
As we already discussed about useState(), and the useEffect() allow us to perform side effect in functional components in React js.
Scenario: From the hard coded array the data get fetched and render on the page (with useState), then with the useEffect() we will update the state of object from an array in every 4 seconds.
Let’s say index.html contains the below statement inside the body tag:
<div id="root"></div>
Next in the index.js file write the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
Now in the App.js file, the App components contain the below set of code:
// import logo from './logo.svg';
import './App.css';
// import UseStateExample from './Components/UseStateExample';
import Data from './Components/Data';
import { useEffect, useState } from 'react';
function App() {
const { employee } = Data;
//set the index of array as 0
let index = 0;
//initial state
const [user, setUser] = useState(employee[index]);
useEffect(() => {
const timer = setInterval(() => {
setUser(updateUser);
}, 4000);
return () => {
clearInterval(timer);
};},[]);
//Updateuser() will update the object until it reached end of array and then it reset this cycle and start all over it again with index=0
function updateUser() {
index = index + 1;
if (index > employee.length - 1) {
index = 0;
}
return employee[index];
}
return (
<div className="App">
<div class="container">
<p >First Name: {user.Firstname}</p>
<p >Last Name: {user.Lastname}</p>
<p >Age: {user.age}</p>
</div>
</div>
);
}
export default App;
Next, the Data.js file contains the below set of array of objects:
const Data = {
employee: [
{
Firstname: 'John',
Lastname: 'Smith',
age: "23"
},
{
Firstname: 'Ron',
Lastname: 'Trump',
age: "35"
},
{
Firstname: 'Alex',
Lastname: 'Church',
age: "52"
}]}
export default Data;
Now run the app with npm start command, and you can see the data get updated every 4 seconds.

This is an example of Dynamic state react js.
Read State in React js
Global state in React JS
Here we will see what is global state and how to use a global state in react JS.
As we know in React JS, the state is used to hold and modified the state value in the react component. In most of React applications, to update the state we need to access the multiple components. This is performed by introducing the global state in the React application.
The global state’s main purpose is to communicate a state among multiple components.
With global state communication can happen in three ways:
- With a child React component
- With a parent React component
- With a sibling React component
The React context provides a way to communicate data between components, without passing the data explicitly with props.
Why we need React context
In React, the state is grasped by the highest parent component in the stack of components that requires to access the state.
To demonstrate we have multiple nested React components. The React component at the top and end of the stack has to access the state.
If the child component wants to access the state from the parent component without context, we need to pass the state as ‘props’ through each child component or nested component, so the process is known as prop-drilling.
And the problem in prop drilling is, let’s say we have 5 components, if the component 2nd, 3rd, and 4th component did not need the state, but still they have to pass the state so that it could reach the 5th component.
This is an example of prop drilling, where we need to pass the state to each component so it can be accessed by the 5th component.
Let’s say index.html contains the below statement inside the body tag:
<div id="root"></div>
Next in the index.js file write the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
Now the App.js file, have the App component containing the below code:
import './App.css';
import Child from './Components/Child';
function App() {
return (
<div className="App">
<Child></Child>
</div>
);
}
export default App;
Now the child.js file contains the Child component, follow the below code:
import { useState } from 'react';
function Child() {
const [employee, setUser] = useState("Alex Smith");
return (
<>
<h1>{`Welcome ${employee}!`}</h1>
<Child2 employee={employee} />
</>
);
}
function Child2({ employee }) {
return (
<>
<h1>Component 2</h1>
<Child3 employee={employee} />
</>
);
}
function Child3({ employee }) {
return (
<>
<h1>Component 3</h1>
<Child4 employee={employee} />
</>
);
}
function Child4({ employee }) {
return (
<>
<h1>Component 4</h1>
<Child5 employee={employee} />
</>
);
}
function Child5({ employee }) {
return (
<>
<h1>Component 5</h1>
<h2>{`Welcome ${employee} again!`}</h2>
</>
);
}
export default Child
Now if we will run the app, we can see the below output render on the page:

The problem can be solved by the create context functionality in React JS-Hooks
To apply to create context functionality, we need to import the Create context and use it in your project.
import { useState,createContext } from 'react';
Then we will use the content provider to wrap the child component and provide the state value. Now all components in the stack can access the user context.
Now to use the context in the child component, we need to access it by using userContext-Hook. To use userContext functionality in the project, we need to import userContext like below:
import { useState,createContext, userContext } from 'react';
Let’s see how to apply to React js context-Hooks in the above example to solve the problem of prop-drilling. So in the Child.js file update the below code:
import { useState,createContext,useContext } from 'react';
const EmployeeContext= createContext();
function Child() {
const [employee, setUser] = useState("Alex Smith");
return (
<>
<EmployeeContext.Provider value={employee}>
<h1>{`Welcome ${employee}!`}</h1>
<Child2 employee={employee} />
</EmployeeContext.Provider>
</>
);
}
function Child2() {
return (
<>
<h1>Component 2</h1>
<Child3/>
</>
);
}
function Child3() {
return (
<>
<h1>Component 3</h1>
<Child4 />
</>
);
}
function Child4() {
return (
<>
<h1>Component 4</h1>
<Child5 />
</>
);
}
function Child5() {
const employee= useContext(EmployeeContext);
return (
<>
<h1>Component 5</h1>
<h2>{`Welcome ${employee} again!`}</h2>
</>
);
}
export default Child
Now to run the app use the npm start command, you can see the above code render on the page.

Read What is react js and react native
React js state and lifecycle
Here we will see React js state and Lifecycle of components.
In Reactjs the Lifecycle method is an important feature to make components more efficient and reusable. Basically, the Lifecycle method is available for Class components, so the class component gets extended to React component to use the Lifecycle method
After releasing of React 16.8 version in March 2019, now it is possible to create a Functional component in React js that is not stateless and we can create a lifecycle method with the help of React Hooks function i.e. useState and useEffect. These functions permit us to set the initial state and use lifecycle events in the Functional component in React.
In React js Lifecycle of components goes through the below cycle:
- Mounting: This is the stage in the Lifecycle method when the initialization of the component is getting completed and the component gets mounted on the DOM element and for the first time rendered on the page. This stage has two such prebuilt functions componentWillMount() and componentDidMount(). The componentWillMount function is invoked right before the component is executed or rendered on the page first time. The componentDidMount function gets invoked right after the rendered or executed for the first time.
- Updating: In this phase, we can update the props and state by the events like clicking and pressing the key on the Keyboard by user. This phase has the following functions that are invoked at different points.
- componentWillReciveProps(): It is a props exclusive function and independent of states. This function gets invoked before the props get reassigned.
- shouldComponentUpdate(): This function gets invoked before rendering an already mounted component when a new state or props are received. Then the subsequent steps rendering will not be carried out if returned false.
- componentWillUpdate(): This function gets invoked right before the rendered function is executed after the updation of props or state.
- componentDidUpdate: This function gets invoked right after the rendered function is executed after the updation of props or state
- Unmounting: This is the last phase of the component lifecycle, this will unmount the component from the DOM element. To unmount we will use the componentWillUnmount function. This function gets invoked once right before the component is removed from the page and this denotes the end of the lifecycle.
Let’s see a Clock example, without the Lifecycle method in Class Component:
Let’s say index.html contains the below statement inside the body tag:
<div id="root"></div>
Next in the index.js file write the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
Now the App.js file, have the App component containing the below code:
import './App.css';
import Child from './Components/Child';
function App() {
return (
<div className="App">
<Child></Child>
</div>
);
}
export default App;
Then in the Clock.js file, Clock is a class component, that comes with a lifecycle method, when the component mounts and unmounts. Whenever the Clock component is rendered to the DOM for the first time, we will set up the timer using Mounting.
And, the DOM constructed by the Clock is removed, when we want to clear the timer using unmount
import{Component} from 'react'
class Clock extends Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
// this lifecycle method get invoked right after the render method executed.
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Time!</h1>
<h2>{this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
export default Clock;
Now, run the above application using the npm start command, and you can see the timer will tick every second on page.

Now we will see how to recreate the above class clock component into a functional component, by applying the lifecycle method with react-Hooks functionality.
So in the Clock component, change the class component with the Functional component.
import React,{useState,useEffect} from "react"
function Clock(){
const[date,setDate]=useState(new Date().toLocaleTimeString());
useEffect(()=> {
setInterval(()=>{
setDate(new Date().toLocaleTimeString())
},1000);
});
return(
<div>
<h1>Time!</h1>
<h2>{date}.</h2>
</div>
)
}
export default Clock;
In the above code, useState() is used to setting the state which means we are deconstructing the used state. It contains two values the current state i.e. date, and function which updates the useState i.e. ‘setDate’ and it accepts one argument i.e. the initial state value(new Date().toLocaleTimeString()) which is set to a new date.
In the next step, we are calling to useEffect() which is similar to componentDidMount and componentWillUnmount. So in this method, we are setting up the interval and updating the state every second using the setDate function. At last, we render the JSX every second on the page based on the current state.
Now run the Application using the npm start command, you can see the timer changing every second.

This is how we can define the state and lifecycle of component in React js.
React js update state from another component
Here we will see how to update React js state from another component using Hooks
To update the state we need to use useCallback()- Hooks, this hook returns a memorized callback function. That means when we have a component in which the child rerendering again and again without need. This hook is useful when we pass a callback to a child component that references equality to avoid unnecessary render.
So here we will use useCallback() to update the state (Ename) from another component(Child component.
Let’s say index.html contains the below statement inside the body tag:
<div id="root"></div>
Next in the index.js file write the below code:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
reportWebVitals();
Now the App.js file, have the App component containing the below code:
import './App.css';
import Child from './Components/Child';
function App() {
return (
<div className="App">
<Child></Child>
</div>
);
}
export default App;
In the Parent component, we provide the Employee name as Alex using useState(), and we will use the child component to update the Employee name with useCallback() hook.
Parent.js
import React, { useState } from 'react';
import Child from './Child';
function Parent(){
const[Ename, setEname]=useState('Alex');
return(
<Child Ename={Ename} onChangeEname={setEname}/>
)
}
export default Parent;
Child.js
import { useCallback } from 'react';
function Child({Ename,onChangeEname }){
const handleInputChange= useCallback(event =>{onChangeEname(event.target.value)},[onChangeEname] )
return (
<div>
<input type="text" onChange={handleInputChange} value={Ename} />
<div><h2>The Employee name is: {Ename}</h2></div>
</div>
)
}
export default Child
Now run the App with the npm start command, you can see the one text box with the initial name on the page. To update the name, type a new name on the text box, and you can see the updated name render on the screen

This is how we can update the state from another component.
Conclusion
In this React js tutorial, we learned about the Hooks concept, with hooks how we can define the state in the functional component, and also we discuss some other usage of hooks in React functional component.
- What are Hooks in React js?
- State in react js functional component
- state management in react js
- usestate in react js
- global state in react js
- dynamic state react js
- react js state and lifecycle
- react js update state from another component
I am Bijay a Microsoft MVP (8 times –Â My MVP Profile) in SharePoint and have more than 15 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com