Hooks in React 18 and 19
Hooks in React 18 and 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 :
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 :
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 :