DEV Community

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

Posted on • Edited on

Redux vs Context API: When to use them

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 deeply nested child requires data from a component higher up in the tree. If we pass on the data through the props, every single one of the children would be required to accept the data and pass it on to its child, leading to prop drilling, a terrible practice in the world of React.

To solve the prop drilling issue, we have State Management Solutions like Context API and Redux. But which one of them is best suited for your application? Today we are going to answer this age-old question!

What is the Context API?

Let's check the official documentation:

In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

Context API is a built-in React tool that does not influence the final bundle size, and is integrated by design.

To use the Context API, you have to:

  1. Create the Context

    const Context = createContext(MockData);
    
  2. Create a Provider for the Context

    const Parent = () => {
        return (
            <Context.Provider value={initialValue}>
                <Children/>
            </Context.Provider>
        )
    }
    
  3. Consume the data in the Context

    const Child = () => {
        const contextData = useContext(Context);
        // use the data
        // ...
    }
    

So What is Redux?

Of course, let's head over to the documentation:

Redux is a predictable state container for JavaScript apps.

It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time-traveling debugger.

You can use Redux together with React, or with any other view library. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available.

Redux is an Open Source Library which provides a central store, and actions to modify the store. It can be used with any project using JavaScript or TypeScript, but since we are comparing it to Context API, so we will stick to React-based Applications.

To use Redux you need to:

  1. Create a Reducer

    import { createSlice } from "@reduxjs/toolkit";
    
    export const slice = createSlice({
        name: "slice-name",
        initialState: {
            // ...
        },
        reducers: {
            func01: (state) => {
                // ...
            },
        }
    });
    
    export const { func01 } = slice.actions;
    export default slice.reducer;
    
  2. Configure the Store

    import { configureStore } from "@reduxjs/toolkit";
    import reducer from "./reducer";
    
    export default configureStore({
        reducer: {
            reducer: reducer
        }
    });
    
  3. Make the Store available for data consumption

    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Provider } from 'react-redux';
    import App from './App.jsx'
    import store from './store';
    
    ReactDOM.render(
        <Provider store={store}>
            <App />
        </Provider>,
        document.getElementById("root")
    );
    
  4. Use State or Dispatch Actions

    import { useSelector, useDispatch } from 'react-redux';
    import { func01 } from './redux/reducer';
    
    const Component = () => {
        const reducerState = useSelector((state) => state.reducer);
        const dispatch = useDispatch();
        const doSomething = () = > dispatch(func01)  
        return (
            <>
                {/* ... */}
            </>
        );
    }
    export default Component;
    

That's all Phew! As you can see, Redux requires way more work to get it set up.

Comparing Redux & Context API

Context API Redux
Built-in tool that ships with React Additional installation Required, driving up the final bundle size
Requires minimal Setup Requires extensive setup to integrate it with a React Application
Specifically designed for static data, that is not often refreshed or updated Works like a charm with both static and dynamic data
Adding new contexts requires creation from scratch Easily extendible due to the ease of adding new data/actions after the initial setup
Debugging can be hard in highly nested React Component Structure even with Dev Tool Incredibly powerful Redux Dev Tools to ease debugging
UI logic and State Management Logic are in the same component Better code organization with separate UI logic and State Management Logic

From the table, you must be able to comprehend where the popular opinion Redux is for large projects & Context API for small ones come from.

Both are excellent tools for their own specific niche, Redux is overkill just to pass data from parent to child & Context API truly shines in this case. When you have a lot of dynamic data Redux got your back!

So you no longer have to that guy who goes:

meme

Wrapping Up

In this article, we went through what is Redux and Context API and their differences. We learned, Context API is a light-weight solution which is more suited for passing data from a parent to a deeply nested child and Redux is a more robust State Management solution.

Happy Developing!

Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja

Thanks for reading

Need a Top Rated Front-End Development Freelancer? Contact me on Upwork

Want to see what I am working on? Check out my GitHub

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on Instagram

Follow my blogs for Weekly new Tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas
  2. Would you mentor me?

    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

  3. Would you like to collaborate on our site?

    As mentioned in the previous question, I am in a time crunch, so I would have to pass on such opportunities.

Connect to me on

Latest comments (37)

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
 
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
 
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
 
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.

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
 
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
 
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
 
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
 
gagandeogan profile image
Gagan ガガン

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

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.