Quick Summary:
The much anticipated React 18 update is here, and here is everything you need to know about âWhatâs New in React 18â. Let us see the latest React 18 features and changes that will revolutionize how the world Reacts!
React v18.0 is here after a long wait and many speculations in the React community about the major updates this version will bring to the developersâ community and the clients as well.
From the beginning, the React team has been very cautious about introducing these groundbreaking upgrades to the React developers at a pace that they can understand, adopt and embrace entirely. They invited a panel of experts, library authors, developers, and educators from various fields to participate in their React 18 Working Group for giving inputs, providing feedback, and collaborating with them on the release. This group aims to prepare the React ecosystem for a smooth, seamless adoption of React 18 for existing libraries and applications.
Now that React 18 is finally out, there are many React 18 new features and changes that will redefine React in the future. There has been major consideration and measures taken to ensure that upgrading your current React project to React 18 doesnât break your existing code. Without further ado, letâs get right into it:
Also Read: ReactJs Advantages and Disadvantages
1. React 18 Concurrent Mode
This is one of the most important React 18 new features that solve an age-old ignored problem in React â concurrency. It is not exactly a feature; however, it works more like a behind-the-curtains function, that powers React to prepare various instances of your UI concurrently (at the same time). Generally, React designs APIs, and hides the implementation details from developers. They believe React developers need to focus on how using React features will help them achieve the user experience they want for their clients and React will figure out how to deliver that experience.
Although, Concurrent React is not just an implementation detail. It is a fundamental React change that updates Reactâs core rendering model which makes it important to understand how Concurrent React works in React 18.
Before React 18, or even before upgrading to React 18 and not enabling concurrent features, updates are rendered in a single, uninterrupted, and synchronous transaction. The problem with asynchronous transactions is once you initiate an update to render, nothing can interrupt it until the result is shown on the userâs screen.
This is not always the case in concurrent rendering. React can very well initiate rendering an update, pause it in middle, or abandon an already in progress rendering update entirely. React guarantees a seamless user experience and consistent UI at all times even when a render is interrupted. This enables React to create new screens behind the scenes without affecting the main thread. Hence the main thread can respond to the user input as soon as it receives it, even if it is stuck in rendering a middle to large update. This creates a seamless user experience.
Another benefit of concurrent React is the reusable state. Through concurrency, React will be able to eliminate sections of the overall UI from the usersâ screen and add them back whenever by reusing its previous state. For instance, when a user changes tabs and returns to the original tab, React will be able to store the state of the original tab in the same state as it was before. React 18 is going to introduce a new component called <Offscreen>
to implement this pattern.
LookinG for React developers to hire?
Get in touch to develop highly scalable web app project.
2. Automatic Batching
React has always used batching for grouping state updates using event handlers and inbuilt hooks. Doing so helps prevent components from unnecessarily re-render for all state updates, which results in improvised performance. Until React 17, batching was only supported for browser events. With the new React 18 release, React is launching an improved version of batching called âAutomatic Batchingâ. Automatic Batching will enable batching for all state updates irrespective of where theyâre coming from with createRoot. This will include batch state updates, asynchronous operations, intervals, native event handlers, and timeouts.
React 17 batching:
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
fetchSomething().then(() => {
// React 17 and earlier versions does NOT batch these because
// they run *after* the event in a callback, not *during* it
setCount(c => c + 1); // Causes a re-render
setFlag(f => !f); // Causes a re-render
});
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}
Here as you can see, as React 17 and previous versions only batched updates after the event is in a callback, it sets both functions to cause a re-render, making the entire React app rerender twice separately.
However, React 18 overcame this limitation by batching updates inside of any promises, timeouts, native event handlers, or any other events just like updates inside React events were handled in React 17. This will significantly reduce unnecessary re-renders, improving application performance:
React 18 Automatic Batching:
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
fetchSomething().then(() => {
// React 18 and beyond WILL batch these:
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
});
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}
Also Read: How to Secure ReactJS App?
Stopping Automatic Batching with flushSync()
Now that we understand the benefits of automatic batching in reducing unnecessary rendering that was happening in React 17 and previous versions, it is also important to have a way to stop automatic batching for code that may depend on reading something directly from the DOM as soon as there is a state change. For this, React 18 has a provision of ReactDOM.flushSync()
that helps developers opt-out of batching:
import { flushSync } from 'react-dom'; // Note: from react-dom, not REACT
function handleClick() {
flushSync(() => {
setCounter(c => c + 1);
});
// React has updated the DOM by now
flushSync(() => {
setFlag(f => !f);
});
// React has updated the DOM by now
}
3. Transitions
Transition is a new concept introduced in React to differentiate between non-urgent and urgent updates. It helps developers set priorities to updates they expect their users to interact with more, or want their users to have a seamless experience with.
Urgent updates reflect direct interactions like clicking, typing, pressing, and so on. Transition updates that transition the UI from one view to another. Urgent updates need an immediate response for matching the userâs intuition and experience when they deal with physical objects. If there is a slight delay when they click a button, it throws them off as they expect an immediate response. Users are more patient with transition updates as they understand that their actions will not provide immediate response on screen, for instance moving from one page to another. For instance, if a user clicks a drop-down menu button, they expect the drop-down menu to appear on click, although the contents of the drop-down menu can load with a slight delay, which is natural for users to understand. Especially when you filter or sort the data according to new attributes, users will be patient with those updates.
Generally, if you want to deliver the user experience, single-user input should result in both an urgent and a non-urgent update. With React 18, developers can use start transition API inside an input event which informs React which updates are urgent and which are just âtransitionsâ. Let us understand how this looks in coding:
import {startTransition} from 'react';
// Urgent: Show what was typed
setInputValue(input);
// Mark any state updates inside as transitions
startTransition(() => {
// Transition: Show the results
setSearchQuery(input);
});
Here updates wrapped inside start transition will be considered non-urgent and will be interrupted if any urgent update from the userâs end like keypress or click comes in. If the transition gets interrupted by the user, React will abandon the mid-rendering task that wasnât finished and prioritize rendering the latest urgent update.
There are two ways to start transitions in React 18:
useTransition â a hook used to start transitions, including a value for tracking the pending state.
start transition â when hooks arenât available, developers can use this method to start transitions.
Are you looking to hire React Native Developers?
Get dedicated React Native experts with ample experience in delivering cost-effective cross-platform mobile app solutions with Aglowid
4. React 18 Suspense Features
React suspense is a React component that helps developers suspend a component being rendered until a certain condition is met, and this displays a fallback option. The fallback option can be a string or other React component such as a spinner. Until now React Suspense would only work with dynamic importing (lazy loading).
import React from 'react';
// Dynamic import()
const CatAvatar = React.lazy(() => import('./path/to/cat/avatar'));
// Displays "loading..." to the user until CatAvatar
// has finished loading.
const AppContainer = () => (
<React.Suspense fallback="loading...">
<CatAvatar />
</React.Suspense>
);
Hence, so far React suspense was being utilized to help developers present a graceful loading state to the users when they experience a delay where the network has finished loading and is executing the next chunk of JavaScript code. Through React Suspense, you could inform your users that the web app is loading the next chunk and the data will be presented to them shortly.
With React 18, developers at React decided to expand the functionality and utility of React suspense, especially integrating it with React 18âs concurrent rendering features we discussed earlier. Now developers can combine React Suspense with transition API. If a transition is suspended, React will prevent the already visible content to be replaced by a set fallback. Instead, React will now delay the rendering for long enough until sufficient data gets loaded for avoiding a bad loading state.
5. New React Strict Mode Behaviours
Strict mode got introduced in React with the React 16.3 build. It was brought to React as a tool for identifying coding patterns that could cause problems with Reactâs concurrent rendering APIs. It runs in development-only mode and shows them error messages or suggestions about their code, so they can refine it better. When developers add <StrictMode>
to a React app, it adds a special behavior to all the components that it is wrapped around. For instance, when developers would run React in âstrict modeâ React would intentionally re-render all components for flushing out any unsafe effects.
With React 18, <StrictMode>
will get additional behaviors and features that allow React to add or remove particular sections of the UI while preserving its state. For doing this React will mount and unmount trees using the same component state as before. This will help React performance optimization out of the box but needs the components to be resilient to the impact of being mounted and destroyed multiple times. Most effects should work without needing to make any changes but some effects assume they are destroyed or mounted once. React 18 strict modes will be able to stimulate unmounting and remounting the component in development mode:
* React mounts the component. * Layout effects are created. * Effect effects are created. * React simulates unmounting the component. * Layout effects are destroyed. * Effects are destroyed. * React simulates mounting the component with the previous state. * Layout effects are created. * Effects setup code runs
6. New React Hooks
And last but certainly not least, there are new React hooks! Â React hooks were made available in October 2018. They provide developers with an alternative to developing class-based components and a different perspective on state management and lifecycle functions. It powers React functional components that make it possible for developers to develop an entire app with it. This helps developers execute simpler codes that implement similar functions in a faster and more effective manner. With React 18, there are many new React hooks introduced such as:
New React Hooks | Description |
useId: | It is a new hook that helps generate unique IDs on both server and client while avoiding hydration mismatches. It is mainly useful for component libraries integrating with accessibility APIs that need unique IDs. |
useTransition & startTransition | Allows developers to mark state updates that are not highly important or urgent. Other states are treated as important when you do so. |
useDeferredValue: | Helps defer re-rendering a non-urgent part of the tree. There is no fixed delay, hence React attempts deferred rendering right after the first render is reflected on screen. This is interruptible and hence doesnât block user input. |
useSyncExternalStore: | Brand new React hook that allows external stores to support concurrent reads by forcing updates to the store to be synchronous. Using with removes the requirement of using useEffect when subscribing to external data sources. |
useInsertionEffect: | Another new React hook that enables CSS in JavaScript libraries to deal with performance issues of injecting styles in the render. This hook gets executed after DOM is mutated and before layout effects read the new layout. |
Wrapping up!
These are the latest developments and changes in React 18 that you should know about. Keep checking this space for more React 18 updates and finding out whatâs new in React as and when it becomes available to public.
have a unique app Idea?
Hire Certified Developers To Build Robust Feature, Rich App And Websites.
Also Check:
This post was last modified on December 11, 2023 5:38 pm