Sobes.tech
Middle+

Have you ever worked with React Context? What are the disadvantages of Context compared to Redux?

sobes.tech AI

Answer from AI

React Context allows passing data through the component tree without explicitly passing props at every level. This is convenient for global settings, themes, localization, etc.

Cons of Context compared to Redux:

  • Lack of centralized state management: Redux provides a single store and strict rules for updating via actions and reducers, which simplifies scaling and debugging.
  • Performance: When the Context value changes, all components subscribed to it re-render, even if they don't need all the data. Redux allows more fine-grained control over updates through selectors.
  • Development tools: Redux has a mature ecosystem of tools (Redux DevTools) for tracking state changes and debugging.
  • Middleware and extensibility: Redux supports middleware for handling asynchronous actions and logging, which is not available in Context.

Example of using 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' }}>Click me</button>;
}