Member-only story

React hooks: using Context API with functional components

Wai Hein
2 min readOct 4, 2020

--

If you are a React developer, you have probably heard about React hooks, https://reactjs.org/docs/hooks-intro.html. Developing React application using State Reducer Pattern is now becoming a trend. If you are using this pattern, you will be using functional components and React context API. This article will show you how to use React Context API to manage the global state and access it from the child functional components.

One scenario we might need to use Context API is that if our application is supporting multiple languages and we need to share the state related to language data across components. For example, all the components in our application need to know the current language. So that we can access the current language from every component within our application.

Let’s get started..!

The code snippets are not complete. They are written just to give you an overall idea of how to use context API with functional components. But it should be enough.

Create a file called LanguageContext.js with the following code.

import React, { createContext, useState } from 'react';const LanguageContext = createContext(true);const LanguageContextProvider = ({ children }) => {
const [currentLanguage…

--

--

Wai Hein
Wai Hein

Written by Wai Hein

8 x AWS Certified Full-stack | DevOps | Serverless Engineer with over a decade of experience

No responses yet