React's state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState
, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state and lifecycle management in functional components, provide a more versatile approach to React development.
There are several built-in hooks in React, today we are going to see new React hooks that are introduced in React 18.
useId:
useId hook is one of the simplest hooks in react js and it is used to generate unique id's for related elements on both client-side and server-side. The useOpaqueIdentifierhook was used before useId but it did contain some bugs and had its limitations with react 18 update react introduced useId with bug fixes.
Importing useId hook:
import { useId } from "react"
Syntax:
const id = useId()
useId does not take any parameters.
Example: below is the practical example of useId hook
JavaScript
import Component from "./Component";
function App() {
return (
<div className="App">
<Component />
<p>
This is Paragraph
</p>
<Component />
</div>
);
}
export default App;
JavaScript
import React, { useId } from 'react'
function Component() {
const id = useId()
return (
<div>
<label htmlFor={id}>Field 1:</label>
<input
type="text"
id={id}
/>
</div>
)
}
export default Component
Output:
OutputuseDeferredValue:
- In React 18, addressing sluggish rendering is a key goal, and
useDeferredValue
and useTransition
hooks are introduced for this purpose. - When rendering a component multiple times for a large number of inputs, React's efficiency can be compromised, leading to delays and slower render times.
useDeferredValue
is a React Hook that postpones updating a portion of the UI. It introduces a delay in updating the hook value, enhancing user experience by preventing immediate rendering and allowing a smoother display of characters as the user types.
Importing:
import { useDeferredValue } from 'react'
Syntax:
const deferredValue = useDeferredValue(value);
Example: below is the practical example of useDeferredValue hook
JavaScript
import React, { useState } from 'react';
import DisplayInput from './DisplayInput';
function App() {
const [userInput, setUserInput] = useState('');
const handleInputChange = (e) => {
setUserInput(e.target.value);
};
return (
<div>
<label htmlFor="userInput">
Enter Text:
</label>
<input
type="text"
id="userInput"
value={userInput}
onChange={handleInputChange} />
<DisplayInput input={userInput} />
</div>
);
}
export default App;
JavaScript
import React,
{ useDeferredValue } from 'react';
function DisplayInput({ input }) {
const deferredValue =
useDeferredValue(input);
const renderInputs = () => {
const inputs = [];
for (let i = 0; i < 20000; i++) {
inputs.push(
<div key={i}>
{deferredValue}
</div>
);
}
return inputs;
};
return (
<div>
<h2>
Displaying
{deferredValue}
</h2>
{renderInputs()}
</div>
);
}
export default DisplayInput;
Output: There is no delay in updation of input in input box.
OutputuseTransition:
useTransition
addresses performance concerns in React applications by enhancing UI responsiveness, ensuring a smoother user experience even during background processing.- In scenarios like a search component with dynamic filtering, where multiple states are updated simultaneously (e.g., search input and filtered results), React's default high-priority updates can lead to potential slowdowns.
- The issue arises when managing numerous user inputs, causing delays in updating states and impacting user interaction.
useTransition
resolves this by allowing low-priority state updates through the startTransition function, preventing UI blocking and optimizing overall performance.
Import:
import { useTransition } from 'react'
Syntax:
const [isPending, startTransition] = useTransition()
Example: below is the practical example of useTransition hook
JavaScript
import React from 'react';
import SearchList from './SearchList';
function App() {
return (
<div>
<SearchList />
</div>
);
}
export default App;
JavaScript
import React, {
useState,
useTransition
} from 'react';
const namesList = [
'Alice',
'Bob',
'Charlie',
'David',
'Eva',
'Frank'
// ... Add more names as needed
];
function SearchList() {
const [searchTerm, setSearchTerm] = useState('');
const [filteredNames, setFilteredNames] = useState(namesList);
const [isPending, setTransition] = useState();
const handleSearch = (e) => {
const term = e.target.value.toLowerCase();
setSearchTerm(term);
setTransition(() => {
const filtered =
namesList.filter(
name =>
name.toLowerCase()
.includes(term)
);
setFilteredNames(filtered);
})
};
return (
<div>
<label htmlFor="search">
Search:
</label>
<input
type="text"
id="search"
value={searchTerm}
onChange={handleSearch}
placeholder="Type to search names" />
<ul>
{
filteredNames.map((name, index) => (
<li key={index}>
{name}
</li>
))
}
</ul>
</div>
);
}
export default SearchList;
Output:

useSyncExternalStore:
- React commonly uses internal states, but
useSyncExternalStore
comes into play when states are managed by third-party libraries or browser APIs outside React. - This hook allows subscription to external stores, like global state in Redux or data in browser APIs (e.g., localStorage), ensuring components re-render upon changes in the external store.
Import:
import { useSyncExternalStore } from 'react'
Syntax:
const variable_name = useSyncExternalStore(subscribe, getSnapshot, [getServerSnapshot]?)
Example: below is the practical example of useSyncExternalStore hook
JavaScript
import React from 'react';
import ResizableElement
from './BatteryStatusIndicator';
function App() {
return (
<div>
<ResizableElement />
</div>
);
}
export default App;
JavaScript
import { useSyncExternalStore } from 'react'
export default function ResizableElement() {
const subscribe = (listener) => {
window.addEventListener('resize', listener)
return () => {
window.removeEventListener('resize', listener)
}
}
const width =
useSyncExternalStore(subscribe,
() => window.innerWidth);
return (
<div>
<p>Size: {width}</p>
</div>
)
}
Output:
OutputuseInsertionEffect:
useEffect
executes a function after component rendering, while useInsertionEffect
is designed for inserting elements into the DOM before layout effects, like dynamic styles, without server rendering.useInsertionEffect
is specialized for pre-layout element insertion, running only on the client side and not during server rendering.
Import:
import { useInsertionEffect } from 'react';
Syntax:
useInsertionEffect(()=>{
// Insert dynamic styles before layout effects fire
return()=>{
//cleanup function
}
}, [])
Example: This exampe implements UseInsertionEffectHook in React
JavaScript
import React from 'react';
import UseInsertionEffectHook from './BatteryStatusIndicator';
function App() {
return (
<div>
<UseInsertionEffectHook/>
<br/>
<br/>
<button>First</button>
<button>Second</button>
</div>
);
}
export default App;
JavaScript
import { useInsertionEffect, useState } from "react";
export default function UseInsertionEffectHook() {
const [theme, setTheme] = useState('dark')
useInsertionEffect(() => {
const styleRule = getStyleRule(theme);
document.head.appendChild(styleRule);
return () => document.head.removeChild(styleRule)
}, [theme])
return <button
onClick={
() =>
setTheme(theme === 'dark' ?
'white' : 'dark')}>
Change theme
</button>
}
const getStyleRule = (theme) => {
const tag = document.createElement('style')
tag.innerHTML = `
button {
color: ${theme === 'dark' ? 'white' : 'black'};
background-color :
${theme === 'dark' ? 'black' : 'white'};
}
`
return tag
}
Output:
Output
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. Why Use React?Before React, web development faced issues like slow DOM updates and mes
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Stateless (before hooks)
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects