React v18 features: useSyncExternalStore

Introduction to React v18's useSyncExternalStore hook

In this lesson, we are going to explore how the newly added useSyncExternalStore hook works and how it simplifies reactivity with external data stores outside React components.

Uday Hiwarale
JsPoint
Published in
11 min readApr 13, 2023

--

(source: unsplash.com)

Before we dive deep into how the useSyncExternalStore React hook works, let’s explore a simple example of reactivity in React. Let’s say we want to design a simple React application that displays the current state of internet connectivity in the user’s device. We can use the navigator.onLine property from the browser's Web API to get this state and use online and offline events on window to listen to this state change.

import { useEffect, useState } from "react";

export default function App() {
const [isOnline, setIsOnline] = useState(navigator.onLine);

useEffect(() => {
const onlineCallback = () => setIsOnline(true);
const offlineCallback = () => setIsOnline(false);

window.addEventListener("online", onlineCallback);
window.addEventListener("offline", offlineCallback);

return () => {
window.removeEventListener("online", onlineCallback);
window.removeEventListener("offline", offlineCallback);
};
}, [])…

--

--

JsPoint
JsPoint

Published in JsPoint

A collection of essential articles for JavaScript, WebAssembly, TypeScript, Node.js, Deno, and Web development in general.

No responses yet