React context API
Created By: chatGPT
The Context API in React is a powerful feature that allows for easier state management by providing a way to share values between components without the need to explicitly pass props down the tree. This is especially useful for global data that many components might need to access, such as user authentication, theme selection, or language preference. The main pieces of the Context API are Context, Provider, and Consumer.
import React, { createContext, useContext, useState } from 'react';
const MyContext = createContext();
const MyProvider = ({ children }) => {
const [state, setState] = useState({
user: null,
theme: 'light'
});
return (
<MyContext.Provider value={{ state, setState }}>
{children}
</MyContext.Provider>
);
};
To use the Context API, you first need to create a context using
createContext()
, then wrap your component tree with a Provider which holds the global state. Components within this tree can access the context values using the useContext
hook.const SomeComponent = () => {
const { state, setState } = useContext(MyContext);
const changeTheme = () => {
setState(prev => ({ ...prev, theme: prev.theme === 'light' ? 'dark' : 'light' }));
};
return (
<div>
<h1>User: {state.user ? state.user.name : 'Guest'}</h1>
<button onClick={changeTheme}>Toggle Theme</button>
<p>Current Theme: {state.theme}</p>
</div>
);
};
Finally, remember to wrap your application with the Provider so that all child components can access the context. This way, instead of passing props down multiple levels, you can access global state directly and cleanly within any component that needs it.
const App = () => {
return (
<MyProvider>
<SomeComponent />
{/* Other components can go here */}
</MyProvider>
);
};