React hooks: using Context API with functional components

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.

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

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

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.

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.

Hope this article is helpful. My name is Wai, Software Engineer. You can reach out to me here, https://www.linkedin.com/in/wai-yan-hein-b99162123/.

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