Using Context API in React with Functional Components
By: Ankomahene Shadrack
Tags: JavaScript, Context Api, React Function Component, React Hook, Reactjs

Using Context API in React with Functional Components

Photo by Andreas Gücklhorn on Unsplash

In this article, We will learn about Context API in React and use it to build a very simple project.

Prerequisite: This article assumes you have basic knowledge in JavaScript, and react, It is however not required to know them before you read.

What is Context API in React?

Context provides a way to pass data through the component tree without having to pass props down manually at every level. — react docs

If you’ve used react for some time or have some level of experience with react, you will know that passing data via props becomes very cumbersome when the props are going to be used by many components within the project and you have to explicitly pass the props down the component tree.

And sometimes, some components would have to receive the props only to pass it down to its children. This is known as Prop Drilling. This adds some sort of complexity to your project and it becomes hard to manage when the project is getting large.

This sort of situation is when Context API proves to be useful. Using Context API in our application, we avoid passing props through intermediate components who do not need the props, “Props Drilling”.

B asically, Context API is designed to share “global” data that can be used in any part of your application without passing props down the component tree.

How to use the Context API

Let’s see how we can use Context API to build this simple user list application.

I used create-react-app to bootstrap the project.

If you want to follow along, you can do npx create-react-app app-name

what we will build:

Simple user list application

It’s a simple application that lets you add a user to the list of users and also remove users.

This is how my file structure looks like:

file structure

You will see that am using three(3) components (User.js, UserList.js, AddUser.js) together with App.js which we will see in a minute what each of them does. You can also see the context.js file which we are going to talk about next.

How to create a context in react.

context.js

creating a context

import { createContext } from 'react';

export const AppContext = createContext();

In the above example, createContext method will help us create a Context instance, which will help us send data to the various components. So we export in order to be able to import and use it in those components.

Let’s see what’s in the App.js file

App.js

You will see that on line 8: const [ users, setUsers ] = useState(userList);

I am using the useState hook to store the list of users.

line 10–21 → dispatchUserEvent(actionType, payload) is a function that receives an actionType(example: ‘ADD_USER’, ‘REMOVE_USER’) and a payload (the actual content) that will add or removed users from the state as seen above.

line 24–29 → in the return block I am doing <AppContext.Provider value={{ users, dispatchUserEvent }}>

The value attribute in the AppContext.Provider tag is the data that is made available to <AddUser /> and <UserList /> components.

This means that in the <AddUser /> and <UserList /> and all their children components, we have access to the list of users and can also dispatch events to add or remove a user.

Let’s now see how we will get and render the list of users from the context in our UserList.js component.

UserList.js

line 6 → Since we are using functional components, we are using the useContext hook which is made available to us by react as seen here const { users } = useContext(AppContext);

And notice how we are passing the AppContext in the useContext hook and also how we are destructuring only the users from the context since we want to render the list of users with this component.

We display the users using a map and render the User.js component for Each user.

User.js

on line 12–16 → we display the user info (ie, name, age, and bio)

on line 5 → we get the dispatchUserEvent from the context.

And on line 7–9 → we dispatch a REMOVE_USER event with the userId as the payload for the button click on line 18. This means each time the button is clicked it will dispatch an event to remove a user from the state using the user’s id.

remember the dispatchUserEvent function?

dispatch user event

Let’s also see how to add a User to the list.

AddUser.js

So here too we have access to the dispatchUserEvent from the Context. const { dispatchUserEvent } = useContext(AppContext);

on line 6–8 → am using useState to keep track of the data coming from the input fields.

And the function handleAddUser() adds the user to the list by dispatching a ‘ADD_USER’ action on button click and passing the user data as payload.

So in the end we have this:

Before You Use Context API

Note that, Context is mainly used when some data needs to be accessible by many components at different nesting levels and you want to avoid passing props down the tree.

Context API is very useful, but you should use it carefully because it can sometimes make component reuse difficult.

You can read more here React Docs — Context

Thank you for reading.