Table of Contents
- Introduction
- What is Concurrent Mode?
- What is useDeferredValue?
- Code Samples Using Concurrent Mode and useDeferredValue
- Conclusion
Introduction
There's been a lot of buzz about React's new features, Concurrent Mode and useDeferredValue. But how do we use these new features? In this post, we will deep dive into these features and explore their usage through actual code samples.
What is Concurrent Mode?
Concurrent Mode is a new feature in React that allows more efficient control over the rendering of your application.
In traditional React, one update task is processed at a time. This mode, in which only one update is processed at a time, means that when a new update occurs, other updates are kept waiting until it is completed. This could result in the application losing its responsiveness and degrading the user experience.
However, by enabling Concurrent Mode, React can process multiple update tasks simultaneously. This allows React to control the priority of updates more flexibly, improving the responsiveness to user interactions such as inputs and clicks.
What is useDeferredValue?
useDeferredValue is a new hook in React that controls rendering in Concurrent Mode.
This hook tells React that a certain value may be delayed in becoming available. React continues to display an alternate value (usually the previous value) instead of waiting for that value to become available.
Here's a basic usage example:
const deferredData = useDeferredValue(someData, { timeoutMs: 2000 });
const isStale = deferredData !== someData;
return (
<>
<LoadingSpinner show={isStale} />
<SomeComponent data={deferredData} />
</>
);
Code Samples Using Concurrent Mode and useDeferredValue
Below is a sample code that combines Concurrent Mode and useDeferredValue.
First, to enable Concurrent Mode, you create a root using ReactDOM.createRoot
.
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Next, create a component that fetches data asynchronously. This component uses the useDeferredValue
hook to tell React that the data may be delayed in becoming available.
function AsyncComponent() {
const [data, setData] = useState(null);
useEffect(() => {
fetchData().then(setData);
}, []);
const deferredData = useDeferredValue(data, { timeoutMs: 2000 });
const isStale = deferredData !== data;
return (
<>
<LoadingSpinner show={isStale} />
<SomeComponent data={deferredData} />
</>
);
}
Conclusion
That's it for a detailed explanation and usage of React's new features, Concurrent Mode and useDeferredValue. By using these new features, you can greatly improve the performance and user experience of your React application. Now, why not try out these new features yourself?
Top comments (1)
So basically it improves performance too right? So what's the difference of using this or Suspense/lazyLoad()?