Geek Culture
Published in

Geek Culture

React 18 new features

React 17 was focused on improving the fundamentals but there are few important things that got added in React 18. In this article, we will go through some of the latest updates on how to get started with the cool new features in react 18 alpha.

Install React 18 alpha : npm install react@alpha react-dom@alpha

Here is the list of few updates.

  1. New Root API
  2. Suspense
  3. SuspenseList
  4. useDeferredValue
  5. Automatic Batching

New Root API

In React 18 there’s a new Root API.

Earlier in our reactDOM.render method, we use to pass our App component, then document.getElementById and our root element. So we were rendering our app component into our root element on the page.

import ReactDOM from "react-dom";
import App from "App";
ReactDOM.render(<App />, document.getElementById("root"));

In React 18, We first have to create the root through the createRoot method. This is being passed our root element and then we call root.render and pass our app component.

import ReactDOM from "react-dom";
import App from "App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

Here the root of our React app has been separated. We now first need to create the root using the createRoot method and then call the render method on it.

Suspense

Like its name, Suspense suspends something until it’s ready to be rendered.

In the previous version of react, the below code would result in ReadyComponent being immediately mounted and its effects called.

<Suspense fallback={<Loading />}>
<ComponentWaitingForData />
<ReadyComponent />
</Suspense>

This has been taken care of in React 18.

Referring to the above code, Now it won’t mount the ReadyComponent, instead will waiting for ComponentWaitingForData to resolve first.

SuspenseList

A SuspenseList excepts a two prop. ‘revealOrder’ and ‘tail’.

‘revealOrder’ is one of SuspenseList configuration options. It can be undefined, together, forwards, and backwards.

  • undefined (default): reveal children as suspenders resolve.
  • together: reveal children together, once all suspenders are resolved.
  • forwards: render children from top to bottom, indifferent to suspender. resolution order
  • backwards: render children from bottom to top, indifferent to suspender resolution order

‘tail’ props dictates how the unloaded items in a SuspenseList are shown. Its value can either be collapsed or hidden.

<SuspenseList revealOrder="forwards" >
<Suspense fallback={<p>Loading attendance...</p>}>
<Attendance id={facultyID}/>
</Suspense>
<Suspense fallback={<p>Loading homework...</p>}>
<Homework id={facultyID}/>
</Suspense>
</SuspenseList>

The above code with SuspenseList demonstrates that we can set the revealOrder to force the attendance to appear first and then the homework section.

<SuspenseList revealOrder="forwards" tail="collapsed">
<Suspense fallback={<p>Loading attendance...</p>}>
<Attendance id={facultyID}/>
</Suspense>
<Suspense fallback={<p>Loading homework...</p>}>
<Homework id={facultyID}/>
</Suspense>
</SuspenseList>

The above code demonstrates that only one fallback is shown at a time. i.e first the fallback for the attendance and then the fallback for the homework.

useDeferredValue

The ‘useDeferredValue’ is a hook that will return a deferred version of the passed value. It takes in the state value and a timeout in milliseconds. It will return a deferred version of the value that may “lag behind” it for most timeouts.

import { useDeferredValue } from "react";
const [text, setText] = useState("react js");
const deferredText = useDeferredValue(text, { timeoutMs: 2000 });

This is commonly used to keep the UI responsive when we have something that renders immediately based on user input and something that needs to wait for a data fetch.

Automatic Batching

There are huge improvements to automatic batching. In the earlier versions of React, it uses to batch multiple state updates into one to reduce unnecessary re-renders. The problem was it was done only in DOM event handlers and not in promises, timeouts, or other handlers.

Let’s look at the below code on how batching occurs with earlier versions of React.

export default function App() {
const [count, setCount] = useState(0);
const [color, setColor] = useState(undefined);

const handleClick = () => {
setCount(count + 1); //No re-render
setColor(count % 2 === 0 ? "Green" : "Red"); //No re-render
// Now re-renders once at the end (this is batching)
}
return (
<>
<button onClick={handleClick}>Next</button>
<span style={{
color: count % 2 === 0 ? "red" : "green",
}}>
{color}
</span>
</>
);
}

With React 18, promises, timeouts, or other handlers will also take advantage of that. It will batch state updates no matter where they happen. This will result in better performance.

Let’s look at the below code where batching occurs. In the below code batching works fine with React 18 but earlier versions of React will not batch it.

export default function App() {
const [count, setCount] = useState(0);
const [color, setColor] = useState(undefined); const handleClick = () => {
Promise.resolve().then(() => {
setCount(count + 1); //Re-render
setColor(count % 2 === 0 ? "Green" : "Red"); //Re-render
});
} return (
<>
<button onClick={handleClick}>Next</button>
<span style={{
color: count % 2 === 0 ? "red" : "green",
}}>
{color}
</span>
</>
);
}

However, if there is a need where we don’t want our component to be batched, we can opt-out that component using ReactDOM.flushSync().

Reference — https://reactjs.org/blog/2021/06/08/the-plan-for-react-18.html

Closing thoughts:

We just got to know about some of the cool updates in React 18 alpha version. Being a JavaScript developer, I really liked the updates and am excited to see what the beta release of React 18 looks like.

Thank you for being till the end 🙌 . If you enjoyed this article or learned something new, support me by clicking the share button below to reach more people and/or give me a follow on Twitter to see some other tips, articles, and things I learn and share there.

--

--

--

A new tech publication by Start it up (https://medium.com/swlh).

Recommended from Medium

JavaScript Built-In Functions and Objects

Testing an Apollo GraphQL server using apollo-server-testing, Jest and msw

Postman: JSON Schema Validation

Dictionaries

npm Convos: the native web

Cypress Force Visit to a different origin

In this blog post I will explain you one of the confusing feature of Scala for beginners i.e

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amir Mustafa

Amir Mustafa

JavaScript Specialist | Consultant | YouTuber 🎬. | AWS ☁️ | Docker 🐳 | Digital Nomad | Human

More from Medium

How To Easily Test Your React Components

React Programming-Fundamentals

Setting Up React Router

React Concepts