Lecture-11 Notes-3227
Lecture-11 Notes-3227
Context
Context provides a way to pass data through the component tree without having to
pass props down manually at every level. This is the alternative to "prop drilling" or
moving props from grandparent to child to parent, and so on. Context is designed to
share data that can be considered “global” for a tree of React components, such as
the current authenticated user, theme, or preferred language.
React Context API
The React Context API is a component structure that allows us to share data across
all levels of the application. The main aim of Context API is to solve the problem of
prop drilling (also called "Threading"). There are three steps to using React context:
1. Create context - using the createContext method.
2. Provide Context - Setup a Context.provider and define the data which
you want to store.
3. Consume the Context - Use a Context.consumer or useContext hook
whenever you need the data from the store.
Output:
Creating the Context
React.createContext
const MyContext = React.createContext(defaultValue);
Context.Provider
<MyContext.Provider value={/* some value */}>
Every Context object has a Provider React component which allows consuming
components to subscribe to context changes. It acts as a delivery service. When a
consumer component asks for something, it finds it in the context and provides it to
where it is needed. The provider accepts a prop (value), and the data in this prop
can be used in all the other child components. This value could be anything from the
component state.
All consumers that are child components of a Provider will re-render whenever the
Provider’s value prop changes. Changes are determined by comparing the new and
old values using the same algorithm as Object.is.
import { useState } from "react";
import ChildComponent from "./ChildComponent";
import { colorContext } from "../context";
return (
<>
<h1>Pick a color</h1>
<input type="color" onChange={(e) => { setColor(e.target.value);}}
value={color} />
{/* Providing the context to the child component */}
<colorContext.Provider value={{ color, setColor }}>
<ChildComponent />
</colorContext.Provider>
</>
);
};
useContext hook
const value = useContext(SomeContext)
useContext is a React Hook that lets you read and subscribe to context from your
component.It can be used with the useState Hook to share the state between deeply
nested components more easily.
import { useContext } from "react";
import { colorContext } from "../context";
Context.Consumer
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
A React component that subscribes to context changes. Requires a function as a
child. The function receives the current context value and returns a React node. The
value argument passed to the function will equal the value prop of the closest
Provider for this context in the component tree. If there is no Provider for this context,
the value argument will be equal to the defaultValue, which was passed to
createContext().
import React from 'react';
import { colorContext } from "../context";
Custom Provider
It is a component which acts as a provider and it makes use of the default provider.
Custom providers are created using the createContext function from the React
library, which creates a new context object that can be passed down to child
components using a provider component. The provider component is responsible for
passing the context data down to its child components via a special prop called
value.
By using a custom provider, you can centralize the management of shared data and
state in a single place, making it easier to maintain and update your application. This
can be particularly useful when working with complex applications that require a lot
of shared state management, such as e-commerce sites or large data-driven
applications.
For Example:
import { createContext, useState } from "react";
const itemContext = createContext();
function CustomItemContext({children}) {
const [total, setTotal] = useState(0);
const [item, setItem] = useState(0);
return(
<itemContext.Provider value={{total,setTotal,item, setItem}}>
{children}
</itemContext.Provider>
)
}
export { itemContext };
export default CustomItemContext;
function App() {
return (
// providing multiple contexts
<CustomItemContext>
<div className="App">
<h2>Shopping Cart</h2>
<Navbar />
<Items />
</div>
</CustomItemContext>
);
}
export default App;
function useValue() {
const value = useContext(itemContext);
return value;
}
return (
<itemContext.Provider value={{ total, item, handleAdd, handleRemove }}>
{children}
</itemContext.Provider>
);
}
export { useValue };
export default CustomItemContext;
Summarising it
Let’s summarise what we have learned in this Lecture:
● Learned about Prop Drilling.
● Learned how to create Context.
● Learned how to provide Context.
● Learned how to consume the Context.
● Learned how to use multiple contexts.
● Learned about custom providers.
● Learned about custom hooks.
Some References:
● Context: link
● React Context for beginners: link