React useContext hooks

Edison Devadoss
3 min readMay 3, 2020

--

Hi friends, in this article, I will explain the React useContext hook with example.

Google Image

The useContext hook is the one among the basic hooks.

What is useContext?

The React Context is simple and alternative to pass props to down and up level of components. Instead of passing local data around and through several layers of components, it takes a step back to create the global state, which is extremely useful for data that needs to be shared across components (data such as themes, authentication, preferred language, etc.)

We should know about the createContext.

CreateContext

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

Using createContext we can pass the values to the down level of the component tree. If we want to pass a certain value to the entire application, we can use createContext. Earlier we pass the values as props but it is very complicated.

Example

create a react project

$ create-react-app use_context_hooks
$ cd use_context_hooks
$ npm start

After we created the project set our createContext.

https://carbon.now.sh/

Create a provider for context.

https://carbon.now.sh/

This provides the context to the rest of the component (represented by the Toolbar component). No matter how far a component is away from the Toolbar component, as long as it is somewhere in the component tree, it will receive the ThemeContext .

https://carbon.now.sh/

Receive value using the useContext.

https://carbon.now.sh/

In thetheme constant, we received the values that we passed in the Provider.

For the code for Git link click here.

Here I mentioned link for useState hook article click here.

--

--

Edison Devadoss
Edison Devadoss

Written by Edison Devadoss

Software Engineer / Full Stack Developer / JavaScript / React / React Native / Firebase / Node.js / Book Reader

No responses yet