[Shruti Kapoor] What's new in React 18?
React 18 alpha version was just announced. The theme of React 18 is to make the UI more performant by removing janky user experiences by introducing out of the box features and improvements powered by "concurrent rendering". React 18 introduces minimal breaking changes.
Read the full article here for code snippets
Root API
React 18 introduces Root API ReactDOM.createRoot
. Before React 18, we used ReactDOM.render
to render a component to the page. Going forward with React 18, we will use ReactDOM.createRoot to create a root, and then pass the root to the render function. The good news is that your current code with ReactDOM.render
will still work, however, it is strongly recommended to start transitioning to createRoot
as render
will be marked deprecated
starting React 18. The current ReactDOM.render
is only provided to ease the transition to React 18.
Automatic batching ( Out of the box, opt-out available):
Batching is the process of grouping multiple state updates into one to prevent multiple re-renders. Previously, React batched state updates that happened in a single event callback managed by React event system, however state updates that happened outside the event were not batched.
However, with automatic batching, all updates, even within promises, setTimeouts, will be batched.
startTransition (opt-in)
startTransition
can be used to mark UI updates that do not need urgent resources for updating. For eg: when typing in a typeahead field, there are two things happening - a blinking cursor that shows visual feedback of your content being typed, and a search functionality in the background that searches for the data that is typed.
Showing a visual feedback to the user is important and therefore urgent. Searching is not so urgent, and hence can be marked as non-urgent. This is where startTransition
comes into play.
By marking non-urgent UI updates as "transitions" , React will know which updates to prioritize making it easier to optimize rendering and get rid of stale rendering. Updates marked in non-urgent startTransition
can be interrupted by urgent updates such as clicks or key presses.
How to move to React 18?
npm install react@alpha react-dom@alpha
Change React.render to React.createRoot
const rootElement = document.getElementById("root");
ReactDOM.createRoot(<App />, rootElement).render(<App />);
On a personal note
I am extremely honored to be part of React Working Group for React 18. It is such an amazing experience being part of this team of incredibly talented people along with React core members. React core team did a Twitter space and answered some of the common questions of React 18. Check it out.
---
Shruti Kapoor
More tips on Twitter
Join Tech Hustlers on Discord