Member-only story
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…