Using the useContext hook with React 16.8+ works well. You can create a component, use the hook, and utilize the context values without any issues.
What
You can use this approach, no matter how many nested components do you have it will work fine.
// Settings Context - src/context/Settings
import React, { useState } from "react";
const SettingsContext = React.createContext();
const defaultSettings = {
theme: "light",
};
export const SettingsProvider = ({ children, settings }) => {
const [currentSettings, setCurrentSettings] = useState(
settings || defaultSettings
);
const saveSettings = (values) => {
setCurrentSettings(values)
};
return (
{children}
);
};
export const SettingsConsumer = SettingsContext.Consumer;
export default SettingsContext;
// Settings Hook - src/hooks/useSettings
import { useContext } from "react";
import SettingsContext from "src/context/SettingsContext";
export default () => {
const context = useContext(SettingsContext);
return context;
};
// src/index
ReactDOM.render(
,
document.getElementById("root")
// Any component do you want to toggle the theme from
// Example: src/components/Navbar
const { settings, saveSettings } = useSettings();
const handleToggleTheme = () => {
saveSettings({theme: "light"});
};