←
🏠 Home What is new in React 18?
React 18 just released! It mostly includes new features based on the new concurrent renderer. It changes the core rendering model. The key take away is rendering is interruptible! It means React can start a rendering, pause & continue later.
How to update to latest React 18?
- Install latest version
npm install react react-dom
- Replace
ReactDom.render
withcreateRoot
. The change is to (1) improve how we manage roots & (2) allows optional concurrent features. Similarly for server-side rendering, replacehydrate
withhydrateRoot
.
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App />);
- Use
<StrictMode>
to surface concurrency-related bugs
New features
6 new features include:
- Automatic batching
- Transitions
- New suspense features
- New client & server rendering APIs
- New strict mode behaviors
- New hooks
A brief summary of each feature:
Feature | Description |
---|---|
Automatic batching | Group multiple updates into 1 to reduce rendering. This is automatic with createRoot but we can opt-out with flushSync . |
Transitions | Used to distinguish “urgent” & “non-urgent” updates. So now, updates have priorities. The non-urgent updates are wrapped in startTransition . There’s also useTransition . |
New suspense features | Expanding <Suspense> and allow for server-side use. |
New client & server rendering APIs | New client-side APIs: createRoot and hydrateRoot . New server-side APIs: renderToPipeableStream and renderToReadableStream . |
New strict mode behaviors | Add development-only check for check if components are resilient to mounting & destroying multiple times |
New hooks | 5 new hooks! |
New hooks
Hook | Description |
---|---|
useId | To generate unique IDs (client & server-side) for accessibility. Not for generating keys. |
useTransition | Mark some state updates as non-urgent |
useDeferredValue | Defer re-rendering part of the tree. It is interruptible & doesn’t block user input |
useSyncExternalStore | [For libraries] Allow external stores to support concurrent reads |
useInsertionEffect | [For libraries] Allow CSS-in-JS libraries to address performance issues of injecting styles |
Interesting updates
One interesting update coming to a minor version update for React 18 is including <Offscreen>
. It allows us to prepare UI in background and show it once it’s ready for user.
React 18 also includes Server Components that are experimental and they help interactivity of client-side apps with server-side rendering.