React useContext
Created By: chatGPT
React's useContext is a powerful tool that allows you to share values and functions between components without having to pass props down manually at every level. It simplifies the process of managing state and data in your application. Below is an overview of how to use useContext in a React application.
import React, { useContext, useState } from 'react';
// Create a Context
const MyContext = React.createContext();
const MyProvider = ({ children }) => {
const [value, setValue] = useState('Hello from context!');
return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
);
};
In this example, we created a context called MyContext and a provider component called MyProvider. The provider holds some state (
value
) and a function to update that state (setValue
). Now, we can wrap our components with MyProvider to grant them access to the context.const App = () => {
return (
<MyProvider>
<ChildComponent />
</MyProvider>
);
};
To consume the context in a child component, useContext is used. Here’s how you can access the
value
and setValue
in a child component.const ChildComponent = () => {
const { value, setValue } = useContext(MyContext);
return (
<div>
<p>{value}</p>
<button onClick={() => setValue('New value!')}>Change Value</button>
</div>
);
};
Whenever the button is clicked, it calls
setValue
and updates the context. All components that consume MyContext will re-render as necessary, reflecting the new state. This is a clean and efficient way to manage global state in a React application.// Putting it all together
export const MainApp = () => {
return (
<App />
);
};