useGlobalState()

Modularjs provides a powerful hook called useGlobalState, which lets you create shared, persistent state across your components, sessions, and projects.


๐Ÿง  What Is useGlobalState?

Unlike useState, which creates local and temporary state inside a single component, useGlobalState gives you access to a globally shared variable that:

  • ๐Ÿ” Persists across sessions

  • ๐Ÿ“ Works across different projects

  • ๐Ÿ”— Remains in sync between components using the same key


๐Ÿ’ก Example: Shared Counter Across Components

module.exports = ({ useGlobalState }) => {
  const [count, setCount] = useGlobalState('count', 0);

  return (
    <div>
      <h1>Shared Counter</h1>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

In this example, the 'count' ID is used to identify this piece of state globally. Any other component using useGlobalState('count', ...) will access and update the same value.


๐Ÿ†” Providing a Unique Key

Every call to useGlobalState must include an ID:

const [count, setCount] = useGlobalState('count', 0);
const [score, setScore] = useGlobalState('score', 100);
  • ๐Ÿ†” The first argument is the key (a string) used to reference the shared state.

  • ๐Ÿงฎ The second argument is the initial value used if the state is not already saved.

This allows you to organize and reuse state with full control.


โœ… Why Use useGlobalState?

  • ๐Ÿ”’ Persistence: Keeps data between sessions without manual storage

  • ๐Ÿ”„ Synchronization: Reflects updates instantly across all components using the same key

  • ๐ŸŒ Global Scope: Easily share values between unrelated parts of your app


๐Ÿ” Reactivity

  • When you call setCount(), all components using 'count' will re-render with the new value.

  • Changes are automatically saved, so they persist even after restarting the app.


๐Ÿ›  Best Practices

  • โœ… Use useGlobalState for:

    • App-wide preferences (e.g., dark mode, language)

    • Shared flags (e.g., modal visibility)

    • Persistent values (e.g., counters, scores)

  • โŒ Donโ€™t use it for temporary values unique to one component โ€” use useState instead.


๐Ÿš€ Summary

useGlobalState gives you a reliable, consistent way to manage shared data in Modularjs. Just remember:

const [value, setValue] = useGlobalState('your-unique-key', initialValue);

Last updated