Home > Software design >  What are the practical differences between Redux and Context/Providers in React?
What are the practical differences between Redux and Context/Providers in React?

Time:09-29

I'm a new developer and I'm having trouble understanding the importance of Redux when things like createContext, useContext, and Providers exist. In my naive observation it seems like you can do everything Redux can do (minus the state-tracking dev tools extensions) with just a global context provider at the top level component.

For example, something like this:

function App() {
  const [stateOne, setStateOne] = useState();
  const [stateTwo, setStateTwo] = useState();

  return (
    <ContextProvider shared={{
      stateOne,
      setStateOne,
      stateTwo,
      setStateTwo
    }}>
      ...
    </ContextProvider>
  )
}

Now all descendant components have access to global state, which seems like the main point of Redux. Am I missing an important differentiating factor here about Redux?

CodePudding user response:

Context and Redux are very different tools that solve different problems, with some overlap.

Context is not a "state management" tool. It's a Dependency Injection mechanism, whose only purpose is to make a single value accessible to a nested tree of React components. It's up to you to decide what that value is, and how it's created. Typically, that's done using data from React component state, ie, useState and useReducer. So, you're actually doing all the "state management" yourself - Context just gives you a way to pass it down the tree.

Redux is a library and a pattern for separating your state update logic from the rest of your app, and making it easy to trace when/where/why/how your state has changed. It also gives your whole app the ability to access any piece of state in any component.

In addition, there are some distinct differences between how Context and (React-)Redux pass along updates. Context has some major perf limitations - in particular, any component that consumes a context will be forced to re-render, even if it only cares about part of the context value.

Context is a great tool by itself, and I use it frequently in my own apps. But, Context doesn't "replace Redux". Sure, you can use both of them to pass data down, but they're not the same thing. It's like asking "Can I replace a hammer with a screwdriver?". No, they're different tools, and you use them to solve different problems.

For more details, see my posts:

  • Related