DEV Community

Cover image for Redux vs Context API: When to use them

Redux vs Context API: When to use them

Tapajyoti Bose on November 28, 2021

The simplest way to pass data from a parent to a child in a React Application is by passing it on to the child's props. But an issue arises when a ...
Collapse
 
phryneas profile image
Lenz Weber

You are referring to a style of Redux there that is not the recommended style of writing Redux for over two years now. Modern Redux looks very differently and is about 1/4 of the code. It does not use switch..case reducers, ACTION_TYPES or createStore and is a lot easier to set up than what you are used to.

I'd highly recommend going through the official Redux tutorial and maybe updating this article afterwards.

Collapse
 
ruppysuppy profile image
Tapajyoti Bose • Edited

Thanks for pointing it out, please take a look now

Its great to have one of the creators of Redux reviewing my article!

Collapse
 
phryneas profile image
Lenz Weber

Now the Redux portion looks okay for me - as for the comparison, I'd still say it doesn't 100% stand as the two examples just do very different things - the Context example only takes initialValue from somewhere and passes it down the tree, but you don't even have code to change that value ever in the future.

So if you add code for that (and also pass down an option to change that data), you will probably already here get to a point where the Context is already more code than the Redux solution.

Thread Thread
 
ruppysuppy profile image
Tapajyoti Bose

I'm not entirely sure whether I agree on this point. Using context with data update would only take 4 more lines:

  1. Function in Mock data
  2. useState in the Parent
  3. Update handler in initialValue
  4. Using the update handler in the Child
Thread Thread
 
phryneas profile image
Lenz Weber

In the end, it usually ends up as quite some more code - see kentcdodds.com/blog/how-to-use-rea... for example.

But just taking your examples side by side:

  • Usage in the component is pretty much the same amount of code.
  • In both cases you need to wrap the app in a Provider (you forgot that in the context examples above)
  • creating a slice and creating the Provider wrapper pretty much abstract the same logic - but in a slice, you can use mutating logic, so as soon as you get to more complex data manipulation, the slice will be significantly shorter

That in the end leaves the configureStore call - and that are three lines. You will probably save more code by using createSlice vs manually writing a Provider.

Thread Thread
 
ruppysuppy profile image
Tapajyoti Bose

But I had added the Provider in the Context example 😐

You are talking about using useReducer hook with the Context API. I am suggesting that if one is required to modify the data, one should definitely opt for Redux. In case only sharing the data with the Child Components is required, Context would be a better solution

Thread Thread
 
phryneas profile image
Lenz Weber

Yeah, but you are not using the Parent anywhere, which is kinda equivalent to using the Provider in Redux, kinda making it look like one step less for Context ;)

As for the "not using useReducer" - seems like I read over that - in that case I 100% agree. :)

Thread Thread
 
gottfried-dev profile image
Dan

"I am suggesting that if one is required to modify the data, one should definitely opt for Redux." - can you elaborate? What specific advantages Redux has over using reducers with useReducer in React? Thanks!

Thread Thread
 
phryneas profile image
Lenz Weber

@gottfried-dev The problem is not useReducer, which is great for component-local state, but Context, which has no means of subscribing to parts of an object, so as soon as you have any complicated value in your context (which you probably have if you need useReducer), any change to any sub-property will rerender every consumer, if it is interested in the change or not.

Collapse
 
mangor1no profile image
Mangor1no

I myself really don't like using redux toolkit. Feel like I have more control when using the old way

Collapse
 
phryneas profile image
Lenz Weber

Which part of it exactly is taking control away?

Oh, btw.: if it is only one of those "I need the control only 10% of the time" cases - you can always mix both styles. RTK is just Redux, there is absolutely no magic going on that would prevent a mix of RTK reducers and hand-written reducers.

Collapse
 
daaitch profile image
Philipp Renoth • Edited

Referring to your example, I can write a blog post, too:

Context API vs. ES6 import

Context API is too complicated. I can simply import MockData from './mockData' and use it in any component. Context API has 10 lines, import only 1 line.


Then you can write another blog post Redux vs. ES6 import.

There are maybe projects which

  • need to mutate data
  • want smart component updates
  • want time-travel for debugging
  • want a solid plugin concept for global state management

And then there are devs reading blogs about using redux is too complicated and end up introducing their own concepts and ideas around the Context API without knowing one thing about immutable data optimizations and so on.

You can use a react context to solve problems that are also being solved by redux, but some features and optimizations are not that easy for homegrown solutions. I mean try it out - it's a great exercise to understand why you should maybe use redux in your production code or stick to a simpler solution that has less features at all.

I'm not saying, that you should use redux in every project, but redux is not just some stupid boilerplate around the Context API => if you need global state utils check out the libs built for it. There are also others than redux.

Collapse
 
roggc profile image
roggc

Hello, I have developed a library, react-context-slices which allows to manage state through Context easily and quickly. It has 0 boilerplate. You can define slices of Context and fetch them with a unique hook, useSlice, which acts either as a useState or useReducer hook, depending on if you defined a reducer or not for the slice of Context you are fetching.

Collapse
 
adambiggs profile image
adam-biggs

One of the best and most overlooked alternatives to Redux is to use React's own built-in Context API.

Context API provides a different approach to tackling the data flow problem between React’s deeply nested components. Context has been around with React for quite a while, but it has changed significantly since its inception. Up to version 16.3, it was a way to handle the state data outside the React component tree. It was an experimental feature not recommended for most use cases.

Initially, the problem with legacy context was that updates to values that were passed down with context could be “blocked” if a component skipped rendering through the shouldComponentUpdate lifecycle method. Since many components relied on shouldComponentUpdate for performance optimizations, the legacy context was useless for passing down plain data.

The new version of Context API is a dependency injection mechanism that allows passing data through the component tree without having to pass props down manually at every level.

The most important thing here is that, unlike Redux, Context API is not a state management system. Instead, it’s a dependency injection mechanism where you manage a state in a React component. We get a state management system when using it with useContext and useReducer hooks.

A great next step to learning more is to read this article by Andy Fernandez: scalablepath.com/react/context-api...

Collapse
 
kasir-barati profile image
Mohammad Jawad (Kasir) Barati

Can you give me some explanation to what you meant when you wrote Context is DI.

Collapse
 
niche_nt profile image
Nishant Tilve

Also, if you need to maintain some sort of complex state for any mid-level project, you can still create your own reducer using React's Context API itself, before reaching out for redux and adding external dependencies to your project initially.

Collapse
 
kayeeec profile image
Kayeeec • Edited

But you might take a performance hit. Redux seems to be better performance-wise when you intend to update the shared data a lot - see stackoverflow.com/a/66972857/7677851.

If used correctly that is.

Collapse
 
andrewbaisden profile image
Andrew Baisden

Redux used to be my first choice for large applications but these days I much prefer to use the Context API. Still good to know Redux though just in case and many projects and companies still require you to know it.

Collapse
 
l0h1t profile image
Lohit Peesapati

I found Redux to be easier to setup and work with than Context API. I migrated a library I was building in Redux to context API and reused most of the reducer logic, but the amount of optimization and debugging I had to do to make the same functionality work was a nightmare in Context. It made me appreciate Redux more and I switched back to save time. It was a good learning to know the specific use case and limitations of context.

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

I too am a huge fan of redux for most projects!

Collapse
 
shakilahmed007 profile image
Shakil Ahmed

Exciting topic! 🚀 I love exploring the nuances of state management in React, and finding the sweet spot between Redux and Context API for optimal performance and simplicity. What factors do you prioritize when making the choice? 🤔

Collapse
 
lalami profile image
Salah Eddine Lalami

@ IDURAR , we use react context api for all UI parts , and we keep our data layer inside redux .

Here Article about : 🚀 Mastering Advanced Complex React useContext with useReducer ⭐ (Redux like Style) ⭐ : dev.to/idurar/mastering-advanced-c...


Mastering Advanced Complex React useContext with useReducer (Redux like Style)

Collapse
 
upride profile image
Upride Network

Hi, We have build out site in react: upride.in , which tech stack should be better in 2024 as we want to do a complete revamp for faster loading.
if anyone can help for our site that how we can make progress.

Collapse
 
ivanquirino profile image
Ivan Quirino

I would like to point that Context API is not a state management solution, but a dependency injection solution. You can do use it to inject whatever you like, including state. For state, there can be some performance implications if because components that use a context re-render that component every time the context value changes, and that's when state management libraries come in, they with fine grained state updates and rendering by selecting which piece of state to listen

Collapse
 
nlaitan profile image
nlaitan

Context: Specifically designed for static data, that is not often refreshed or updated.
Redux: Works like a charm with both static and dynamic data.

I've working on a complex project only with context, I didn't see this point. Simply using getters and setters (it's the same thing that use useState) in context do all the work. Integrates very well with hooks and custom hooks and also easy to read.

Can you explain why redux it's better at this point?

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

If you work on a huge project (where you are new to the codebase) with context, you will be running up & down the Dom to find the origin of the data

Collapse
 
sayanta2702 profile image
Sayanta Bhattacharje • Edited

I think Redux plays a big role when you need to develop a complex application, that requires to integrate features that have a lot of states or in our case actions. One might argue that we can use useReducer apis inside a context to handle the long and nested states, updating them when particular actions are performed, but then just like reinventing the wheel we are developing something like redux only. What I understand is both are two different ways of using the context and reducer features that React provides, we can choose which one to use.

But when there is the case of fetching data from server, I think the latest RTK (Redux Toolkit) is very far ahead as it gives a solution to integrate apis, and render data into state, which in case of context apis, we have to manually integrate it

Collapse
 
sjanjan profile image
lijian

I hate redux, It is very complicated

Collapse
 
aralroca profile image
Aral Roca

Try Teaful github.com/teafuljs/teaful 😊

Collapse
 
changtimwu profile image
Tim Wu

I compared the two 3 years ago. At that moment Context API was still new but obviously the winner IMO.

Collapse
 
scottscalablepath profile image
Scott Cosentino

There are some great benefits to using Context API. Context API works best for small projects, where large amounts of debugging isn't required. Our developers broke down a few specific use cases where Context API is the better choice.

Collapse
 
mohitm15 profile image
Mohit Maroliya
Collapse
 
bnnguyen335 profile image
Big size

i’m come back .the team for me .i love you.how old are you. it me dont fine.the team help me last time . thank

Collapse
 
priolo profile image
priolo

try to take a look at this
github.com/priolo/jon

Collapse
 
gagandeogan profile image
Gagan ガガン

As you can see in your example you have created a provider that provider iteself uses
react.context api

Collapse
 
gpt-prompt-coder profile image
Josh the Coder

Wow, this article really inspires me a lot.

Good post, Tapajyoti!

Collapse
 
vaidasviper profile image
Vaidas Viper

Presently the Revival segment looks acceptable for me - concerning the examination, I'd in any case say it doesn't 100 percent stand as the two models simply do altogether different things - the Setting model just takes initialValue from some place and passes it down the tree, however you don't have code to change that esteem ever from now on.

So on the off chance that you add code for that (and furthermore pass down a choice to change that information), you will presumably currently here reach a place where the Setting is now more code than the Revival arrangement.