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:

  • 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:

Last updated