React Context API and Higher-Order Components

Developing a { connect } pattern

Shems Eddine
SHEMSEDDINE on Code

--

You may have come across React’s Context API without realizing it. Same goes for Higher-Order-Components.

If you have ever worked with Redux, you would have experienced both, React’s Context API (under the hood) and Higher-Order-Component, { connect} from their react-redux package. Or @material-ui/core with their withStyles

Both of these concepts are not very difficult but I think realizing when to use them is the difficult part.

In the application I was working on, I had a client object that was used to store system wide defaults and settings as well as reusable objects (the application I was building also had the concept of a middlware so the objects within it could change based on the middlewares injected)

Our scenario

We will be working on the “theme” for our application. We have an object that stores our default theme which our pages can use.

This scenario can be built entirely with React’s Context API.

Context API

Let’s get started by create a file called ThemeContext.js

import React from 'react';export default React.createContext();

--

--

Shems Eddine
SHEMSEDDINE on Code

Azure Cloud Platform Expert | NodeJS & .NET Senior Consultant | Startup CTO in City of London