Sobes.tech
Middle+

What is React Context, when to use it, and when is a state manager preferable?

sobes.tech AI

Answer from AI

React Context is a mechanism for passing data through the component tree without having to explicitly pass props at every level. It is useful for global settings such as theme, localization, current user.

When to use React Context:

  • For a small amount of global data that rarely changes.
  • When you want to avoid "prop drilling" (passing props through many levels).

When to use a state manager (Redux, MobX, Zustand, etc.):

  • If the application is large and complex, with many states and complex update logic.
  • When centralized state management with debugging, middleware, undo/redo, etc., is needed.

Example of using React Context:

const ThemeContext = React.createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  return <ThemedButton />;
}

function ThemedButton() {
  const theme = React.useContext(ThemeContext);
  return <button style={{ background: theme === 'dark' ? '#333' : '#ccc' }}>Button</button>;
}

Thus, Context is good for simple cases of global state, and a state manager is suitable for complex applications with many interactions.