How To Use The useContext API In React
By: Yasas Sandeepa
Tags: Usecontext, Context Api, Typescript, React Hook, React

1. What is state management?

If you are familiar with some old react ( just before introducing the hooks -v16.8 ) we used state as a memory to keep whatever variables we used inside the class. State as the simplest terms, it is a JavaScript object that represents the part of a component that can change as a result of the user’s action.

In a typical React app, when a user executes an action and changes a component’s state, it may have an impact on the state of other components as well. This isn’t so bad when the app is simple. However, the more complex it grows, the more difficult it becomes to keep track of all the dependencies.

Normally we are passing data as props in components. But imagine you have to get some value all around the components and if you pass it from props, you will go crazy. That is not the practice when doing such a scenario.

Bad way of managing the state

This is known as prop drilling, where you’re passing the data from one component to another and you end up passing the data via props through intermediate components that do not even necessarily need them.

So what would be the solution? Here the Context comes to the action. Context API provides a better way to share values between components without having to explicitly pass a prop through every different nesting level of the component tree.

2. A better way to manage the state

According to the official React documentation:

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

The context API is a way to pass data from top component to bottom ones, without manually transferring it to via props. This is fundamentally utilized when some data needs to be accessible by numerous components at different nesting levels. Using Context API and Hooks together gives you very simple and ultimate global state management for your App.

Right way of managing the state

As you can see in the diagram, only the needed components are getting the data. This will ultimately increase the performance of your app.

How Context API works

Context API can be applied in many scenarios. Here are sample use cases of it and you can see the immense area is covered by this little thing.

Theme changing

Multilingual application

Authentication Provider

Notification Provider

What about Redux then. Doesn’t it provide a better solution rather than context? Here comes the battle!

3. Redux vs Context

There are some doubts that this Context API looks like Redux. Some are saying that it is kind of a mini-redux. Let’s dig deep into that for clearing things up.

Technically, Redux is not limited to usage in React apps. It’s actually another open-source library that can be used with any other view libraries like Angular, Vue, Polymer, Ember, Backbone, etc. But most developers associate Redux with React. So you have to install extra packages in order to use redux in your react application.

Context API is specifically made and optimized for React and coming as a build-in facility. So we don’t need to install any extra dependency and can directly be used in React but unable to use in other libraries/frameworks.

Redux is having 3 main building blocks

Store — Holds the application state. In any Redux application, there is only one store. Action — Plain JavaScript object that describes an event (user interactions, API calls, form submissions, etc) that happened in the application and transport the new data to the stores. Each Action must have a type and an optional payload key that contains the data. Reducer — Functions that take the current state of an application, perform an action, and return a new state.

Context API cuts down the complex structure that has in Redux and provides the same functionality as simple as possible.

Context — Global data container that maintains the state. Provider — Enables the consumers to subscribe to the context changes. Consumer — Getter to context.

You can now understand the complexity of Redux (packed with advanced and heavy component structure) and how simple is the Context API.

Redux as you saw is a kinda complex tool with a relatively steep learning curve. It’s mainly using in large-scale applications and is considered as the Industry Standard. (But these things may change like there are more competitors are coming to the action such as GraphQL and the Apollo Client.) It takes time to understand, remember, and get used to its patterns.

Does that mean we, as designers, should stay far away from it? Absolutely No! You should definitely try out that to increase your knowledge. I would like to write a separate article for Redux and hope it will help you to gain some better knowledge in Redux.

One important thing to mention that most people are screaming that redux requires too much boilerplate code, have to add a lot of packages to get Redux … like that. As for the solution to address these common issues Redux Toolkit was introduced. It will efficient Redux development and can be known as a Starter Kit for Redux. Try out redux toolkit official documentation for more info.

But the newest Context API with hooks is above all and we can easily set up it and is as effective as Redux. Moreover, Context API is the in-built solution, So you don’t need to worry about third parties implementing new changes and will not increase your bundle size.

Let’s make things practical!

4. Getting Started

Alright! Let’s build a simple app for understanding the concepts well. I created a theme changer application and it can change the background theme according to our wish.

To create a new React project with the TypeScript template, you can run:

npx create-react-app theme-changer--template typescript

or else

yarn create react-app theme-changer --template typescript

Here comes the package managers. You can use either npm or Yarn. These two package managers are relatively closer together in terms of functionalities but I mostly prefer yarn because,

Performance — the speed of installing dependencies. Security — handles the lock file in a way you would expect.

You can find benchmark testings in the net and Yarn way better performed than npm. However, it’s ultimately your choice. Pickup a one whatever you like.

NPM vs Yarn Cheat Sheet — Credits shift.infinite.red

Alright! Let’s move on to the app by removing the boilerplate code. I created a sidebar and few more components for the app to be more elegant and understandable.

For the sidebar, I have added the react-router to route my components. As I promised to guide you the React router as well and here comes the time to it.

Install the react-router package and add types for typescript.

yarn add react-router-dom

yarn add @types/react-router-dom

Now you have to wrap the app with BrowserRouter to add the ability to route the components. Then you need to define the Route and add a switch for routing between the matching components. Also, you can make a separate router.tsx for this purpose. But I stick with minimal changes.

As you can see I created three components. First I created the left navigation and it will be common for all other components.

You can use the Link to navigate to the relevant path and it will render a fully accessible anchor tag with the proper href Why we use it because if we use <a href> tag instead of that, the page gets reloaded when navigating to the URL. As react is a single page application, it is not the right way to navigate. So use the Link to navigate and avoid the hassle.

I didn’t include the styling for here as CSS files are having more numerous lines and it may get distracted when reading. You can simply copy the styles and class names from here. Make sure to add the class names as well.

For my main page, I created a simple welcome page and likewise for the about pages. Hope it may not be needed to attach here and you can find the two-component here.

Hey, wait for a sec, what is that component called ThemeChanger ?😕 Ah, Don’t worry! I’ll describe this at the end of the article.

If you are done with setting up the environment, let’s move on to the main content. 😍