Blog>
Snippets

Subscribing to a Redux State in a Hook

Use useSyncExternalStore to subscribe to a Redux store's state changes inside a custom React hook.
import { useSyncExternalStore } from 'react';
import { store } from './yourReduxStore'; // replace with the path to your Redux store

// Custom hook to subscribe to the Redux store state
function useReduxState(selector) {
  const getSnapshot = selector
    ? () => selector(store.getState())
    : store.getState;

  const subscribe = store.subscribe;

  // Using useSyncExternalStore to subscribe to the Redux store
  const state = useSyncExternalStore(subscribe, getSnapshot);

  return state;
}

export default useReduxState;
This piece of code creates a custom hook named useReduxState using the useSyncExternalStore hook to subscribe to a Redux store's state changes. The selector function is used to select the part of the state that is of interest. You should import your actual Redux store and pass the appropriate selector function when you use useReduxState.