DEV Community

Saravanan s
Saravanan s

Posted on

usecontext and what is prop drilling in react

what is usecontex
the useContext hook in React provides a way to consume values from a React Context within functional components.
It is a powerful tool for sharing data across the component tree without the need for "prop drilling,"
where props are manually passed down through multiple levels of nested components.

  1. Create a Context: First, you need to create a Context object using React.createContext(). This object will hold the data you want to share.

// MyContext.js
import React, { createContext } from 'react';

export const MyContext = createContext('default value'); 
// You can provide a default value here, which will be used if no Provider is found.


Enter fullscreen mode Exit fullscreen mode

2. Provide the Context Value:

        Wrap the parent component (or the part of your component tree) that needs access to the context with MyContext.Provider. 
The value prop of the provider will be the data th3. Consume the Context Value:at child components can consume.
Enter fullscreen mode Exit fullscreen mode

3. Consume the Context Value:
any child component (even deeply nested ones) that needs to access the context data,
import useContnext and the MyContext object. Then,
call useContext(MyContext) to retrieve the value.

what is prop drilling
the process in React and similar frameworks where data is passed down through multiple nested components
, even if those intermediate components don't need the data themselves
, to reach a deeply nested child component that does

how to use prop drilling
ass props down through intermediate components that don't need them, creating a direct line from a parent component to a deeply nested grandchild component that does need the data.

THIS IS THE MY UNDERSTAND OF THE USECONTEXT AND PROP DRILLING

Top comments (0)