0% found this document useful (0 votes)
49 views

Hooks in React 18 and 19

The document provides an overview of new hooks introduced in React 18 and experimental hooks in React 19, focusing on performance and user experience enhancements. Key hooks in React 18 include 'useId', 'useTransition', and 'useDeferredValue', which improve ID management, update deferral, and handling large updates respectively. React 19 introduces experimental hooks like 'useOptimistic' and 'useFormStatus' aimed at optimizing UI updates and simplifying form management.

Uploaded by

ashkarali.assain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Hooks in React 18 and 19

The document provides an overview of new hooks introduced in React 18 and experimental hooks in React 19, focusing on performance and user experience enhancements. Key hooks in React 18 include 'useId', 'useTransition', and 'useDeferredValue', which improve ID management, update deferral, and handling large updates respectively. React 19 introduces experimental hooks like 'useOptimistic' and 'useFormStatus' aimed at optimizing UI updates and simplifying form management.

Uploaded by

ashkarali.assain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Overview on hooks in React 18 and React 19.

Introduction:
React, a leading JavaScript library for building user interfaces,
introduced several new hooks in React 18, enhancing
performance and development ease. Hooks like ‘useId’,
‘useTransition’, and ‘useDeferredValue’ help manage unique
IDs, defer non-urgent updates, and handle large updates
efficiently. React 19 experimental version introduces new hooks
like ‘useOptimistic’, ‘useFormStatus’ and ‘use’ which are
focused on user experience and data handling.
React 18 Hooks:
1. useId :
The useId hook generates unique IDs that are stable across the
server and client. This is useful for accessibility features that
require unique IDs.
Example:
import React, { useId } from 'react';
const Component = () => {
const id = useId();
return (
<div>
<label htmlFor={id}>Username</label>
<input id={id} type="text" />
</div>
);
}
Explanation: ‘useId’ ensures that the same ID is used during the
initial server render and subsequent client-side rehydration,
avoiding mismatches.

2. useTransition :

The useTransition hook allows you to mark updates as non-


urgent, improving the perceived performance by delaying less
critical updates.

Example:
import React, { useState, useTransition } from 'react';
function MyComponent() {
const [isPending, startTransition] = useTransition();
const [value, setValue] = useState('');
const handleChange = (e) => {
startTransition(() => {
setValue(e.target.value);
});
};
return (
<div>
<input type="text" onChange={handleChange} />
{isPending ? <p>Updating...</p> : <p>Value: {value}</p>}
</div>
);
}
Explanation: ‘useTransition’ is useful for deferring updates that
don't need to be immediate, thus making the UI more responsive.

3. useDeferredValue :

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.

Example:
import React, { useState, useDeferredValue } from 'react';
const MyComponent = () => {
const [input, setInput] = useState('');
const deferredInput = useDeferredValue(input);
return (
<div>
<input type="text" onChange={(e) =>
setInput(e.target.value)} />
<p>Deferred Value: {deferredInput}</p>
</div>
);
}
Explanation: ‘useDeferredValue’ helps in handling large updates
more smoothly by deferring them, thus preventing jank in the UI.
React 19 Hooks (Experimental) :
1. useOptimistic (Optimistic UI Updates) :
useOptimistic Create a seamless user experience by
displaying an optimistic UI update while asynchronous operations
(e.g., data fetching) are in progress.
Takes a callback function that executes the asynchronous
operation and returns the expected data. Immediately updates
the UI based on the assumed successful outcome.Reverts the UI
to the previous state if the operation fails.
Example:
import { useOptimistic } from 'react';
const LikeButton = () => {
const [isLiked, setIsLiked] = useState(false);
const handleClick = useOptimistic(async () => {
const response = await fetch('/api/like');
const data = await response.json();
setIsLiked(data.liked);
}, [isLiked]); // Dependency array to re-run on like state change
return (
<button onClick={handleClick}>
{isLiked ? 'Unlike' : 'Like'}
</button>
);
};
2. useFormStatus (Form Handling Status):
useFormStatus is used to access the current status (pending,
success, error) of a form within a component, simplifying form
management.
It expects the parent form element to be within the same
component hierarchy and returns an object with properties like
pending (indicates ongoing form submission), data (contains
submitted form data upon success), and error (holds any errors
encountered).
Example:
import { useFormStatus } from 'react';
const MyForm = () => {
const { pending, data, error } = useFormStatus();
const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission logic here
};
return (
<form onSubmit={handleSubmit}>
{/* Form fields */}
{pending && <p>Submitting...</p>}
{error && <p>Error: {error.message}</p>}
{data && <p>Form submitted successfully!</p>}
<button type="submit">Submit</button>
</form>
);
};

Conclusion :

In this session, we explored the powerful hooks introduced in


React 18: ‘useId’, ‘useTransition’, and ‘useDeferredValue’.
These hooks offer significant enhancements in managing unique
IDs, deferring non-urgent updates, and handling large updates
more efficiently, thereby improving performance and user
experience.
We also speculated on potential new hooks in the upcoming
React 19 release, such as ‘useOptimistic’, ‘useFormStatus’
and ‘use’ for the streamline data fetching, form handling, and UI
updates, resulting in a more intuitive and responsive user
experience. But these hooks are currently experimental.

You might also like