Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Build a Shared State Manager for React: Step-by-Step

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through building a lightweight shared state manager for React from scratch, without external libraries. You'll create a central store that multiple components can read from and update, with automatic re-rendering when state changes. This approach is ideal for small to medium apps where you want to avoid the overhead of Redux or Zustand but still need shared state beyond local component state.

What You'll Need

  • Node.js and npm installed on your machine
  • A React project set up (e.g., via Create React App or Vite)
  • Basic familiarity with React hooks (useState, useEffect, useSyncExternalStore)

Step-by-Step

  1. Create the store file. In your src folder, create a new file called store.js. This will hold the shared state and the logic to subscribe and update it.
  2. Define the initial state. Inside store.js, declare an object with the initial state you want to share. For example: const initialState = { user: null, count: 0 };
  3. Set up the state and listeners. Use let state = initialState; to hold the current state, and const listeners = new Set(); to track all components that are subscribed to changes.
  4. Create a getState function. This function simply returns the current state. It’s used by React to read the latest value. Example: export function getState() { return state; }
  5. Create a setState function. This function accepts a new state or an updater function (like in useState). It updates the state and then notifies all listeners. Implementation: export function setState(update) { state = typeof update === 'function' ? update(state) : update; listeners.forEach(listener => listener()); }
  6. Add a subscribe function. This function takes a callback and adds it to the listeners set, returning an unsubscribe function. Example: export function subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }
  7. Create a custom hook. In the same file, export a hook named useStore that uses React’s useSyncExternalStore to subscribe to the store and get the latest state. Example: import { useSyncExternalStore } from 'react'; export function useStore() { return useSyncExternalStore(subscribe, getState); }
  8. Use the store in components. Import useStore and setState in any component. Call const state = useStore(); to read the shared state, and call setState({ ...state, count: state.count + 1 }) to update it. The component will re-render automatically when the state changes.
  9. Test with a simple counter. Create a component that displays the count from the store and a button that increments it. Verify that clicking the button updates the count in all components that use the store.
  10. Extend with actions (optional). To keep logic organized, you can export action functions that call setState. For example: export function increment() { setState(s => ({ ...s, count: s.count + 1 })); } Then components just call increment() instead of directly manipulating state.

Common Mistakes

  • Mutating state directly. If you do state.count = 1 instead of using setState, React won’t know the state changed and won’t re-render. Always use setState and return a new object.
  • Forgetting to unsubscribe. If you don’t return the unsubscribe function from subscribe, or if your custom hook doesn’t use it correctly, you’ll have memory leaks as components unmount. The useSyncExternalStore hook handles this automatically, so it’s best to use it.
  • Using the store outside React. If you call getState() in a regular function (like a timer) and expect the component to update, it won’t. You need to trigger a re-render by using the hook or by manually subscribing.

Tips

  • Keep state flat. Nested objects are harder to update immutably. Consider normalizing your state shape.
  • Use functional updates. When updating state based on the previous state, always use setState(s => ({ ...s, count: s.count + 1 })) to avoid stale closures.
  • Separate store logic. Put your store in a dedicated file and import it where needed. This makes it testable and reusable.
  • Consider multiple stores. If your app has distinct domains (e.g., user, cart), you can create separate store files for each, keeping them small and focused.
  • Use TypeScript. Defining types for your state and actions prevents many bugs and improves developer experience.

Troubleshooting

  • Component doesn’t re-render. Check that you’re using useStore() inside the component, not just reading getState(). Also ensure that setState is called with a new object reference, not a mutation.
  • State updates but multiple components get different values. This can happen if you have multiple store instances. Make sure you’re importing from the same store.js file and not duplicating the code.
  • React warns about “Cannot update a component while rendering a different component.” This occurs if you call setState during the render phase. Move such calls into event handlers or useEffect.
  • Unsubscribe function not working. If you manually subscribe and call the unsubscribe function, but the listener is still called, check that you’re deleting the correct listener (the one you added). The Set.delete method works by reference, so you must pass the exact function.

Frequently Asked Questions

Is this better than using Context?

Context is fine for low-frequency updates, but it causes all consumers to re-render when the context value changes. This store approach gives you more control and can be more performant for high-frequency updates, though it requires a bit more setup.

Can I use this with React Server Components?

This store is client-side only. Server Components cannot use hooks, so you’d need to keep the store usage in client components or use a library like Zustand that supports server components.

How do I handle async actions?

You can create async functions that call setState after a promise resolves. For example: async function fetchUser() { const user = await api.getUser(); setState(s => ({ ...s, user })); }

Does this work with React Native?

Yes, as long as you use the same React hooks and JavaScript environment, it works the same way.

Can I persist the state to localStorage?

Yes, you can call setState with the saved state on initialization, and add a listener to save the state whenever it changes. For example, in your store file, you can load from localStorage and subscribe to save on changes.

Is this production-ready?

For small to medium apps, yes. It’s simple and reliable. For very large apps with complex state, you might want a more battle-tested solution like Redux or Zustand, but this approach is a great learning exercise and works well for many use cases.