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.
Published in
11 min readApr 13, 2023
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);
};
}, [])…