Skip to main content

useContext hook

Published 1 min readMarkdown
useContext hook

The useContext uses the object that is created by the createContext hook.

How this works is that lets first create a context. import {useContext,createContext} from 'react';

1)The first step is to create a context and the context can be created as:

let Context=createContext(null);

We can pass anything as a parameter in the the createContext function and whatever is passed it doesn't matter because anyways it is going to be overridden.

This Context contains a provider and this provider is just a react component or we can say a tag which we must include as a parent of other components

The

It contains a prop which is the value that we need to pass and this value is accessible by all the child components which is super cool

This will be clear with the help of an example where we create a small application which changes the color of the child component;

This is the context.js file:

image.png

This is the App.jsx file:

image.png

This is the HomeChild.jsx file:

image.png

image.png

Outputs:

image.png

image.png

From the above code sample we can notice that we were able to access the obj object in the Child component as well without using props with the help of useContext hook.

No comments yet. Be the first to comment.

More from this blog