Search code examples
solid-js

Difference between `createContext()` and `createSignal()` for global state


In solid-js, what is the benefit of using context, when we can create a signal and import it's getter/setter/even a memoized value from a store global store-like file?:

// ./store/myValue.js
export const [value, setValue] = createSignal('');

To my understanding it is totally ok to import this value in multiple components and the reactivity would be maintained throughout those.

The only use-case of the store/global that I can think of, is if your state grows to such a complexity, that you need a more structured context-like approach to improve maintainability, readability etc.


Solution

  • Context in Solid is a scoped object that wraps its child scopes. The main benefit of context is you can re-write a context value at different levels of the component tree. It other words, you can have different values in different contexts, all at the same time.

    Check this example below. We can switch theme as you go deeper into the component tree. A global store will give you the same value at every level.

    const ThemeContext = createContext<string>('black');
    
    const Child = () => {
      const theme = useContext(ThemeContext);
      return (
        <div style={{ color: theme }}>Child Component</div>
      );
    };
    
    const App = () => {
      return (
        <div>
          <Child />
          <ThemeContext.Provider value='red'>
            <Child />
            <ThemeContext.Provider value='blue'>
              <Child />
            </ThemeContext.Provider>
          </ThemeContext.Provider>
        </div>
      );
    }
    
    render(App, document.querySelector('#app'));
    

    This will output:

    <div>
      <div style="color: black;">Child Component</div>
      <div style="color: red;">Child Component</div>
      <div style="color: blue;">Child Component</div>
    </div>