How to implement Context API like Redux in React App

Antony Raj
3 min readMay 15, 2020

--

What is Context API?

The Context API is a component structure provided by the React framework, which enables us to share specific forms of data across all levels of the application. It’s aimed at solving the problem of prop drilling.

“Prop drilling (also called “threading”) refers to the process you have to go through to get data to parts of the React Component tree.”

When to use Context API?

The Context API is useful for sharing data that can be considered global, such as the currently authenticated user, the theme settings for the application, and more. In situations where we have these types of data, we can use the Context API and we don’t necessarily have to use extra modules.

In fact, any situation where you have to pass a prop through a component so it reaches another component somewhere down the tree is where you can use the Context API.

So how do we use it?

How to use the Context API?

With the new Context API, several new functions have been added to the mix creating giving us a rich tool to work with. If you’ve previously attempted to use the old (experimental, do not use) Context API, you may have come across some methods. However, let’s look at some code snippets on how we can use the Context API.

In this example, we will create a simple todo list using the Context API.

You can use create-react-app to create a sample project to work with

codewithme@anto react -> npx create-react-app project_name

This above line of the script creates a new react project in your specific folder.

Create a new file createContext.js (up to you)

import { createContext } from "react";export const TodoContext = createContext();

imports createContext from react package and assign it to a constant by initializing it.

create a new file store.js

export const initalState = {    
todos: [
'setup webpack',
'create a base ',
'implementing design'
]; // dummy data
};

Just created an object with an array to todos(“ dummy data ”).

create a new file reducer.js

export const todoReducer = (state, action) => {  
switch(action.type) {
case 'ADD_TODO':
return {
...state,
todos: [...state.todos, action.payload]
}
case 'DELETE_TODO':
return {
...state,
todos: state.todos.filter((todo, index) => {
return index !== action.payload);
}
}
default:
return state;
}
}

Created a function that gets two parameter. because reducer will always get two parameter first with a state which consists of data and second with action the data that is sent from any action that has been made by the user. Any data that could be sent in this ( i prefer and suggest the redux method by sending Object with two keys such as type and payload)

{
type: 'SET_VALUE',
payload: Data
}

Create a new file contextProvider.js

how to use useReducer

import React, { useReducer } from "react";
import { initalState } from "../store/todo";
import { todoReducer } from "../Reducer/todo";
import { TodoContext } from './todoContext';
const Todo = props => {
const [state, dispatch] = useReducer(todoReducer, initalState);
return (
<TodoContext.Provider value={{ state, dispatch }}>
{props.children}
</TodoContext.Provider>
);
};
export default Todo;

Import all the three context, store and reducer, and import useReducer from react library.

the useReducer requires two parameters that we have already created a reducer function ( todoReducer ) and an initial state ( initalState). And it returns back an array with two values Current State and dispatch function.

The state and dispatch can be shared with the specific components by wrapping with the created context.Provider to make it behave like that make the context provider as a parent component for the specific child component so that we could get access to state and dispatch from that component.

Wrapping the child component.

import TodoContextProvider from './context/todoProvider';const index = () => {
return (
<TodoContextProvider>
<App />
</TodoContextProvider>
);
}

I have wrapped the entire app with context provider so that we will get access to state and dispatch at any point in the application.

https://github.com/codeWithAnto/React-Context-Api/

To know more explore the sample project in the link above 👆

If you have any questions feel free to comment in the comment section below.

--

--

Antony Raj

I’m a deeply passionate young programmer. You’ll probably find me honing my programming skills.In my spare time I contribute to these domains using my skills.