Redux vs Context API: When to use them
Tags: webdev, javascript, react, redux
Published: 2021-11-28 06:01:17

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

    ```js
    const Context = createContext(MockData);
    ```

2. Create a **Provider** for the **Context**

    ```js
    const Parent = () => {
        return (
            <Context.Provider value={initialValue}>
                <Children/>
            </Context.Provider>
        )
    }
    ```

3. Consume the data in the **Context**

    ```js
    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**

    ```js
    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**

    ```js
    import { configureStore } from "@reduxjs/toolkit";
    import reducer from "./reducer";

    export default configureStore({
        reducer: {
            reducer: reducer
        }
    });
    ```

3. Make the **Store** available for data consumption

    ```js
    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**

    ```js
    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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/smhdsuy15m79b3r6v3yf.png)

# 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**](https://www.instagram.com/the.dollar.ninja/)

# Thanks for reading

Need a **Top Rated Front-End Development Freelancer**? Contact me on [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)

Want to see what I am working on? Check out my [GitHub](https://github.com/ruppysuppy)

I am a freelancer who will start off as a **Digital Nomad** in mid-2022. Want to catch the journey? Follow me on [Instagram](https://www.instagram.com/tapajyotib/)

Follow my blogs for **Weekly new Tidbits** on [Dev](https://dev.to/ruppysuppy)

**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](https://dev.to/ruppysuppy/front-end-developer-roadmap-zero-to-hero-4pkf)
    2. [Front End Project Ideas](https://dev.to/ruppysuppy/5-projects-to-master-front-end-development-57p)

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

-   [LinkedIn](https://www.linkedin.com/in/tapajyoti-bose/)
-   [Portfolio](https://tapajyoti-bose.vercel.app)
-   [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)
-   [GitHub](https://github.com/ruppysuppy)
-   [Instagram](https://www.instagram.com/tapajyotib/)