December 11, 2024
React 19: <context> as a Provider and Other Updates
1. Context as a Provider
React 19 introduces a simpler way to use context by allowing Context to be rendered directly as a provider, instead of using Context.Provider.
Example:
const ThemeContext = createContext('');
function App({ children }) {
return (
<ThemeContext value="dark">
{children}
</ThemeContext>
);
}
Benefits:
Cleaner Syntax: Reduces boilerplate by eliminating the need for Context.Provider.
Future Transition: Context.Provider will be deprecated in upcoming versions, and a codemod will be provided for migration.
2. Cleanup Functions for Refs
React now supports returning a cleanup function from ref callbacks, which enhances ref management by adding an explicit cleanup mechanism.
Example:
<input
ref={(ref) => {
console.log('Ref created:', ref);
return () => {console.log('Ref cleaned up:', ref)};
}}
/>
Key Changes:
Deprecation of Null Callbacks: Previously, React would call ref callbacks with null during cleanup. Now, if a cleanup function is provided, React skips this step.
TypeScript Updates: Returning anything other than a cleanup function from a ref callback is now rejected, preventing unintentional issues.
Migration Tip:
Replace implicit returns in ref callbacks:
- <div ref={current => (instance = current)} />
+ <div ref={current => { instance = current; }} />
A codemod (no-implicit-ref-callback-return) will be available for automated fixes.
3. useDeferredValue Initial Value
React 19 enhances the useDeferredValue hook by adding support for an initialValue option, improving performance during the first render.
Example:
function Search({ deferredValue }) {
const value = useDeferredValue(deferredValue, ''); // Initial value is ''
return <Results query={value} />;
}
How It Works:
Initial Render: Returns the initialValue immediately.
Deferred Update: Triggers a re-render in the background once the deferredValue is resolved.
Use Case:
This helps improve the perceived performance of components that handle delayed state updates, such as search bars or autocomplete fields.
Why These Changes Matter
The new <Context> syntax simplifies and streamlines Reactââ¬â¢s context usage.
Cleanup functions for refs make DOM management more predictable and efficient.
Initial values in useDeferredValue enhance responsiveness in user interfaces with deferred state updates.
For more information, see the official React docs
98 views