JAVASCRIPT

Integrate with External State Managers Using useSyncExternalStore

Learn to use React's useSyncExternalStore hook for efficiently subscribing to and reading from external, mutable state sources like custom store implementations.

import React, { useSyncExternalStore, useState } from 'react';

// --- A simple external store implementation ---
// (This could be any external state management library or browser API)
const createStore = (initialState) => {
  let state = initialState;
  const listeners = new Set();

  return {
    getState: () => state,
    subscribe: (listener) => {
      listeners.add(listener);
      return () => listeners.delete(listener); // Unsubscribe function
    },
    setState: (newState) => {
      state = { ...state, ...newState };
      listeners.forEach((listener) => listener());
    },
  };
};

const myExternalStore = createStore({ count: 0, message: 'Hello' });

// --- React Component using useSyncExternalStore ---
function CounterWithExternalStore() {
  // Subscribe to the external store
  const state = useSyncExternalStore(
    myExternalStore.subscribe, // How to subscribe to changes
    myExternalStore.getState   // How to get the current snapshot
  );

  const increment = () => {
    myExternalStore.setState({ count: state.count + 1 });
  };

  const changeMessage = () => {
    myExternalStore.setState({ message: state.message === 'Hello' ? 'World' : 'Hello' });
  };

  return (
    <div style={{ padding: '20px', border: '1px solid #eee', borderRadius: '8px' }}>
      <h3>External Store Integration</h3>
      <p>Count: <strong>{state.count}</strong></p>
      <p>Message: <strong>{state.message}</strong></p>
      <button onClick={increment} style={{ marginRight: '5px' }}>Increment Count</button>
      <button onClick={changeMessage}>Toggle Message</button>
    </div>
  );
}

// Usage example:
// function App() {
//   return <CounterWithExternalStore />;
// }
How it works: `useSyncExternalStore` is a React Hook designed to efficiently subscribe to an external store or mutable source of data. It ensures that your component re-renders whenever the external store updates, while also handling edge cases like concurrent rendering and server-side rendering consistently. It requires two arguments: a `subscribe` function (which takes a callback and returns an unsubscribe function) and a `getSnapshot` function (which returns the current state of the store). This hook is ideal for integrating React components with non-React state management libraries or browser APIs that provide a mutable state.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs