React hooks: using Context API with functional components

If you are a React developer, you have probably heard about React hooks, 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.

const LanguageContext = createContext(true);class LanguageContextProvider extends Component {       constructor(props) {           super(props);           this.state = {               currentLanuage: "en",           }       }      changeLanguage = (lan) => {           this.setState({              currentLanguage: lan           })      }      render() {         return <LanguageContext.Provider value={{ currentLanguage: this.state.currentLanguage, changeLanguage: this.changeLanguage }}>
}}const consumer = LanguageContext.Consumerexport { LanguageContextProvider, consumer as LanguageContextConsumer, LanguageContext };

As you can see, I set the default language as English, “en”.

Then I wrapped my application component with the LanguageContextProvider component as follow.

    render() {         return (             <LanguageContextProvider>                <React.Fragment>                   //other components will be rendered here                </React.Fragment>             </LanguageContextProvider>        )    }}

Imagine that we want to change the language from one of the components, called Navigation.js, we can do so by calling the changeLanguage function of LanguageContextProvider class as follow.

     return (       <LanguageContextConsumer>
{ context => (
<button onClick={() => { context.changeLanguage(context.currentLanguage == 'en'? 'mm': 'en') }}>Change Language</button>

As you can see, we access the values of the provider using LanbuageContextConsumer. When we change the language, the other components can also access the current language in the same way we access the current language from the Navigation component.

But in the Navigation component, we access the current language using LanguageContextConsumer component when we render the view. What if we need to retrieve the current language from somewhere else in the component? We can do it as follow.

    return (        <span>Current language is {languageContext.currentLanguage}</span>

Hope this article is helpful. My name is Wai, Software Engineer. You can reach out to me here,

Software Developer based in the UK, used to work in Singapore, but originally from Myanmar.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store