Exploring the useSyncExternalStore Hook in React.js with Real-Life Examples

Love Trivedi
ZestGeek
Published in
4 min readAug 14, 2024

--

Exploring the useSyncExternalStore Hook in React.js with Real-Life Examples

React.js continues to evolve, introducing new hooks that enhance the way we manage state and side effects in our applications. One such hook is useSyncExternalStore, a powerful tool designed to help you subscribe to external stores and synchronize state updates seamlessly. In this article, we'll dive deep into useSyncExternalStore, explore its usage, and look at practical, real-life examples where this hook can be a game-changer.

What is useSyncExternalStore?

The useSyncExternalStore hook is a new addition to React 18, specifically created to manage state that comes from an external source, such as a global store, a WebSocket, or a database. It provides a consistent way to subscribe to an external data source and re-render your component when the data changes.

Here’s a basic outline of the hook:

const state = useSyncExternalStore(subscribe, getSnapshot);
  • subscribe: A function that registers a callback to be called whenever the external store changes.
  • getSnapshot: A function that retrieves the current state from the external store.

Why Use useSyncExternalStore?

Before React 18, managing external stores with hooks like useEffect or useState was common but often led to issues like stale closures, race conditions, or inconsistent state updates. useSyncExternalStore solves these problems by providing a more stable and consistent approach.

Some of the benefits include:

  • Consistency: Ensures that state updates are synchronized across components.
  • Stability: Prevents unnecessary re-renders and stale closures.
  • Efficiency: Reduces boilerplate code required to manage external data sources.

Real-Life Examples of useSyncExternalStore

Let’s explore some practical scenarios where useSyncExternalStore can be effectively utilized.

Example 1: Integrating with a Global State Management System

Suppose you have a global state management system like Redux or MobX, and you need to synchronize state across multiple components. useSyncExternalStore can be used to connect your components to the global store.

Here’s how you can implement it:

import { useSyncExternalStore } from 'react';
import { store } from './store';

function useGlobalState(selector) {
return useSyncExternalStore(
store.subscribe,
() => selector(store.getState())
);
}

function UserComponent() {
const user = useGlobalState(state => state.user);

return (
<div>
<h1>Welcome, {user.name}!</h1>
</div>
);
}

In this example, useGlobalState connects the component to the global state, ensuring that it re-renders whenever the selected state changes.

Example 2: Real-Time Data from WebSocket

If you’re building a real-time application, such as a chat app or stock ticker, you may need to keep your UI in sync with a WebSocket connection. useSyncExternalStore can help you manage this efficiently.

import { useSyncExternalStore } from 'react';

const socket = new WebSocket('wss://example.com/socket');

function useWebSocketData() {
return useSyncExternalStore(
(onStoreChange) => {
socket.onmessage = (event) => {
onStoreChange(JSON.parse(event.data));
};
return () => socket.close();
},
() => socket.readyState === WebSocket.OPEN ? socket.data : null
);
}

function StockTicker() {
const stockData = useWebSocketData();

if (!stockData) return <div>Loading...</div>;

return (
<div>
<h2>Stock Price: {stockData.price}</h2>
</div>
);
}

In this scenario, the useWebSocketData hook subscribes to the WebSocket and updates the component whenever new data arrives.

Example 3: Syncing with Browser APIs

Consider a scenario where you need to sync your React component with a browser API, such as the window size or navigator status. useSyncExternalStore can simplify this by providing a clear and consistent way to handle such updates.

import { useSyncExternalStore } from 'react';

function useWindowSize() {
return useSyncExternalStore(
(onStoreChange) => {
window.addEventListener('resize', onStoreChange);
return () => window.removeEventListener('resize', onStoreChange);
},
() => ({ width: window.innerWidth, height: window.innerHeight })
);
}

function WindowSizeComponent() {
const { width, height } = useWindowSize();

return (
<div>
<h2>Window Size: {width}x{height}</h2>
</div>
);
}

In this example, the component automatically updates whenever the window is resized, reflecting the current window dimensions.

Conclusion

The useSyncExternalStore hook is a versatile tool that simplifies the process of synchronizing your React components with external data sources. Whether you're working with global state management, real-time data streams, or browser APIs, this hook can help you maintain consistent and efficient state updates across your application.

By leveraging useSyncExternalStore, you can reduce boilerplate code, avoid common pitfalls like stale closures, and ensure that your components remain in sync with the latest data.

At Zestgeek Solutions Private Limited, we specialize in building high-performance, scalable React applications. Whether you’re a startup looking to implement the latest React features or an established company aiming to optimize your existing codebase, our team of experts is here to help. Contact us today to learn how we can take your web and mobile applications to the next level!

--

--

Love Trivedi
ZestGeek

Full Stack Developer | Problem Solver | Knowledge Share, 🚀 Expertise: JavaScript enthusiast specializing in ReactJS, Angular, and Node.js.