In React.js, managing and utilizing context is a powerful way to share values like themes, authentication status, or any other global state across components without the need to pass props manually through every level of the component tree.
Here's a basic guide on how to use context in React:
jsx// context.js
import { createContext } from 'react';
const MyContext = createContext();
export default MyContext;
Wrap your component tree with a Provider
to supply the context value.
jsx// App.js
import React from 'react';
import MyContext from './context';
const App = () => {
const contextValue = {
// Your context data goes here
data: 'Hello from context!',
};
return (
<MyContext.Provider value={contextValue}>
{/* The rest of your components */}
</MyContext.Provider>
);
};
export default App;
Use the useContext
hook to consume the context in your components.
jsx// SomeComponent.js
import React, { useContext } from 'react';
import MyContext from './context';
const SomeComponent = () => {
const contextValue = useContext(MyContext);
return (
<div>
<p>{contextValue.data}</p>
</div>
);
};
export default SomeComponent;
Provider
should wrap the components that need access to the context.useContext
is used to access the current context value.jsx// context.js
import { createContext } from 'react';
const MyContext = createContext();
export default MyContext;
jsx// App.js
import React from 'react';
import MyContext from './context';
import SomeComponent from './SomeComponent';
const App = () => {
const contextValue = {
data: 'Hello from context!',
theme: 'light',
// other values...
};
return (
<MyContext.Provider value={contextValue}>
<SomeComponent />
</MyContext.Provider>
);
};
export default App;
jsx// SomeComponent.js
import React, { useContext } from 'react';
import MyContext from './context';
const SomeComponent = () => {
const contextValue = useContext(MyContext);
return (
<div>
<p>{contextValue.data}</p>
<p>{contextValue.theme}</p>
</div>
);
};
export default SomeComponent;
This way, SomeComponent
can access values from the context without having to pass them down through props.