import React, { useContext, createContext } from 'react'
const ThemeContext = React.createContext()
function Title() {
const theme = useContext(ThemeContext)
const style = {
background: theme.primary,
color: theme.text,
}
return <h1 style={style}>Title</h1>
}
function Nested() {
return <Title />
}
function NestedTwice() {
return <Nested />
}
export default function App() {
const theme = {
primary: 'dodgerblue',
text: 'white',
}
return (
<ThemeContext.Provider value={theme}>
<NestedTwice />
</ThemeContext.Provider>
)
}
export const AuthContext = createContext(INITIAL_STATE);
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, INITIAL_STATE);
useEffect(() => {
localStorage.setItem("user", JSON.stringify(state.user));
}, [state]);
return (
<AuthContext.Provider
value={{
user: state.user,
isFetching: state.isFetching,
error: state.error,
dispatch,
}}
>
{children}
</AuthContext.Provider>
);
};
export default AuthContext;
import React, { useContext } from "react";
import ColorContext from "./colorcontex.ts";
const MyComponent = () => {
const colors = useContext(ColorContext);
return <div style={{ backgroundColor: colors.blue }}>...</div>;
};import React, { useContext } from "react";
const MyComponent = () => {
const colors = useContext(ColorContext);
return <div style={{ backgroundColor: colors.blue }}>...</div>;
};