Overview
React 19 introduces a major update focused on reducing the amount of code developers need to write, while enhancing overall app performance. This version leverages a new React compiler to automate optimization processes, making it easier to build and manage React applications.
Installation
React 19 is not yet a stable release. You can install the canary version to start using these new features:
npm install react@canary react-dom@canary
Major Changes and New Features
- The React Compiler The React compiler is a significant addition in React 19. It converts React code into optimized JavaScript, improving app performance and reducing the need for manual performance optimization techniques.
Key Benefits:
Automatic Optimization: No need to use useCallback, useMemo, or memo to prevent unnecessary re-renders.
Simplified Code: Cleaner and more maintainable codebase.
Example Before React 19:
const increment = useCallback(() => setCount(count + 1), [count]);
const doubleCount = useMemo(() => count * 2, [count]);
Example After React 19:
const increment = () => setCount(count + 1);
const doubleCount = count * 2;
2. Simplified Ref Handling
In React 19, the forwardRef function is no longer necessary for passing refs to child components.
Example Before React 19:
const MyComponent = forwardRef((props, ref) => {
return <div ref={ref}>Hello</div>;
});
Example After React 19:
const MyComponent = (props) => {
return <div ref={props.ref}>Hello</div>;
};
3. The use Hook
The new use hook can resolve promises or context, replacing the need for useEffect and useContext.
Fetching Data with use Hook:
Example Before React 19:
useEffect(() => {
fetchData().then(data => setData(data));
}, []);
Example After React 19:
const data = use(fetchData());
Reading Context with use Hook:
Example Before React 19:
const user = useContext(UserContext);
Example After React 19:
const user = use(UserContext);
4. Directives
Directives specify where React components should run: on the client or the server.
Usage Example:
// Top of your component file
"use client"; // or "use server"
5. Actions
Actions are functions called when a form is submitted. They simplify form handling and can be executed on the server or client.
Client-Side Action Example:
"use client";
const handleSubmit = async (formData) => {
alert(`You typed: ${formData.get('inputName')}`);
};
<form action={handleSubmit}>
<input name="inputName" />
<button type="submit">Submit</button>
</form>;
6. useFormStatus Hook
The useFormStatus hook provides information about the status of form submissions, such as whether a submission is pending.
Example Usage:
const MyForm = () => {
const { pending } = useFormStatus();
return (
<form action={formAction}>
<input name="inputName" />
<button type="submit" disabled={pending}>Submit</button>
{pending && <span>Submitting...</span>}
</form>
);
};
7. useFormState Hook
The useFormState hook is similar to useState, but it uses an action function to set the new state.
Example Usage:
const [state, formAction] = useFormState(addToCart, initialState);
const addToCart = (prevState, formData) => {
const itemId = formData.get('itemId');
if (itemId === '1') {
return { message: 'Added to cart' };
} else {
return { message: 'Could not add to cart, item is sold out' };
}
};
<form action={formAction}>
<input type="hidden" name="itemId" value="1" />
<button type="submit">Add to Cart</button>
<div>{state.message}</div>
</form>;
8. useOptimistic Hook
The useOptimistic hook provides optimistic updates, ideal for real-time apps.
Example Usage:
const [messages, addOptimisticMessage] = useOptimistic(initialMessages, (state, newMessage) => [
...state,
{ text: newMessage, sending: true },
]);
const handleMessageSubmit = async (formData) => {
const message = formData.get('message');
addOptimisticMessage(message);
await sendMessageToServer(message);
};
<form action={handleMessageSubmit}>
<input name="message" />
<button type="submit">Send</button>
</form>;
Conclusion
React 19 brings significant improvements by automating performance optimizations and simplifying code structure. By reducing the need for manual performance hooks and offering new features like directives, actions, and the use hook, React 19 allows developers to write cleaner and more efficient code.