It’s 2023 Now! React State Management: Context or Redux, Which Side Are You On?

Hi there. Today, I am going to discuss when to use what and why. Before I lay down my points and the foundation of my discussion, I would like to first get all of us on the same page about what…

Hi there. Today, I am going to discuss when to use what and why. Before I lay down my points and the foundation of my discussion, I would like to first get all of us on the same page about what Context API and Redux are doing respectively.

Context API

One liner: Context provides a way to pass data through the component tree without having to pass props down manually at every level. Full explanation: Context API enables the passing of data and functions throughout a component tree without manual props transmission at each level. It facilitates sharing of information that is global to a set of React components, such as user authentication state, theme, or language. The API provides an effective management system for shared data, making it accessible to components that require it, without the hassle of props passing. This results in code that is more maintainable and easier to comprehend. To get started with Context API, there is no additional package or library required, it is a built-in feature in React. You can just simply follow these 4 simple steps to set it up.

  • Create a Context in a separate file
import React, { createContext, useContext } from "react";

interface ThemeContextProps {
  theme: string;
  setTheme: (theme: string) => void;
}

const ThemeContext =
  createContext <
  ThemeContextProps >
  {
    theme: "light",
    setTheme: () => {},
  };

2. Create a Provider for the Context that you have created in step 1.

import React, { useState } from "react";
import ThemeContext from "./ThemeContext";

const ThemeProvider = ({ children }: { children: React.ReactNode }) => {
  const [theme, setTheme] = useState("light");

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

export default ThemeProvider;

3. Use the Context in your React component

import React, { useContext } from "react";
import ThemeContext from "./ThemeContext";

const ThemeToggler = () => {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <div>
      <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
        Toggle Theme
      </button>
    </div>
  );
};

export default ThemeToggler;

4. Wrap your component with the Provider that you have created in step 2.

import React from "react";
import ThemeProvider from "./ThemeProvider";
import ThemeToggler from "./ThemeToggler";

const App = () => {
  return (
    <ThemeProvider>
      <ThemeToggler />
    </ThemeProvider>
  );
};

export default App;

You have just implemented Context API into your React application with a feature to toggle the theme anywhere in your application without prop drilling. 👏🏼

Redux

One liner: Redux is a state management library for JavaScript applications that provides a centralised store for the application state. Full explanation: Redux provides a centralised way to manage the state of JavaScript applications. It has a store that stores the application’s state, and actions and reducers to manage changes to the state. By following a unidirectional data flow, Redux makes it easier to build and maintain large and complex applications, and to understand the current state of the application. The library can be integrated with different front-end frameworks, including React, Angular, and Vue.js. To get started with Redux, you just need to follow these 5 simple steps.

  • Install Redux Library
npm install @reduxjs/toolkit react-redux

2. Create a Slice.

import { createSlice, PayloadAction } from "@reduxjs/toolkit";

interface State {
  count: number;
}

const initialState: State = {
  count: 0,
};

const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    increment: (state) => {
      state.count += 1;
    },
    decrement: (state) => {
      state.count -= 1;
    },
  },
});

export const { increment, decrement } = counterSlice.actions;

export default counterSlice.reducer;

3. Create a redux Store with the Slice that you have created above.

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';

const store = configureStore({
  reducer: {
    counter: counterReducer
  }
});

export default store;

4. Connect the Store that you created above to your React components

import React, { useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import { increment, decrement } from "./counterSlice";
import store from "./store";

const Counter = () => {
  const count = useSelector((state: any) => state.counter.count);
  const dispatch = useDispatch();

  const handleIncrement = useCallback(() => {
    dispatch(increment());
  }, [dispatch]);

  const handleDecrement = useCallback(() => {
    dispatch(decrement());
  }, [dispatch]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
      <button onClick={handleDecrement}>Decrement</button>
    </div>
  );
};

export default Counter;

5. Lastly, wrap your component with a Provider from Redux library and point the store argument to the store that you have created above.

import React from "react";
import { Provider } from "react-redux";
import store from "./store";
import Counter from "./Counter";

const App = () => {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
};

export default App;

You have just implemented Redux in your React application to manage the state of the counter. 🎉

Context API or Redux

Now that we have laid down the foundation and implementation of both Redux and Context API, let us see a simple comparison on these 2 state management tools.

Comparison between Redux and Context API As you can see from the comparison table, different tool is suitable for different use cases. Over engineering a small scale application to use Redux might be an over-estimate. Similarly, under engineering a large scale application to use Context API might be problematic as well. The good news is that we can always strike a balance between the two state management tools, both of them can co-exist in a single React application.

Summary

Hope that this article has provided you an insight into what Redux and Context API state management tools are about. Your reluctance to adapt to another state management tool might be causing your React application to be slow and non-performant. Remember that React is a very small and flexible library that allows developers to exercise their own choices, so please check if your current React state management tool is suitable for your application. If not, please change it to another suitable state management tool and make your React application great again! 💯 Do let me know in the comments below if you have other state management tools for React that you think will benefit us, I would love to learn about it. Cheers. 😎

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics