What is Context API and Build Dark Mode App with it

Batista Oliveira
3 min readJul 19, 2020

--

Typical React application pass the data top-down or (parent to child) via props, but it can be complicated for certain type of data that are need for many components.

ContextAp is feature of react that enable to share data between components, it create a context and provide a data that you want to share, without pass props top-down(parent to child).

Context API turn some of your data global to your application to avoiding props drilling that is a situation when you pass the props down to many child components until get to the component that you want use the data, at some time you pass props for those that does not need the data and it create some confusion when you want to manipulate the data or make some changes on your app.

There are a lot of tools that solve that problems like Redux, Flux and Mobx that are the state management tools for React, these tools are used when you got so many states that needs to be global and need some big manipulation of state such as manipulating user’s object or a cart of products and so on.

The Context API is used for the data that is considerate global such as UI theme, idiom preference and authenticated user.

Real Life Example

We got a trend on UI theme that is a Dark Mode of Application, we will build a simple App with Dark Mode using Context API.

Demo of the Dark Mode App

Note: we will use jquery module, I assume that you already know about it and how to install in React.

How to create Context:

At first we got to create a file where our data that we assume that is global will be.

The importants line are commented with explanation

DarkModeContext.js
DarkModeContext.js

After we created our context we can start use that adding as a container to components where we want to share its , in that case I’ll add in App.js you can add it anywhere you want depending on your needs.

App.js

Note: you can create your own style of DarkMode class and add to it

Now we got our component inside of the DarkModeProvider, then we can start make use of the context value.

navbar.js

Content.js

The context API can be used for a lot of stuffs and you can combine with other state manegament tool.

So, that’s ! it got a lot of things to explain but I tried to make more short, I hope you like it and don’t forget the claps, any questions of error you can write the response , peace 💫 !

This is the code if your want to check mine https://github.com/BatistaTony/Simple-Dark-Mode-App

--

--

Batista Oliveira

Software Engineer, Typescript, React, React Native , I love coding and learn new stuffs