I have a top-level component that uses a library to determine whether a user’s browser is in light or dark mode. It’s then being used to set the theme for the app, which include HTML Canvas components (this is important because those do not act like normal React components). Currently, the canvas components do not show the correct theme without a re-render (either a page reload or a hot reload in dev mode).
How do I get the App
component to re-render without a reload? For example, in local dev mode, just the component re-renders when I hit save, and this is the exact behavior I’d like to replicate in the app.
According to other answers on SO, useReducer
is the correct way to force a re-render in a functional component, but the following does not work for me:
function App(props) {
// this is not working
const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
useEffect(() => {
setDarkMode(getColorTheme() === "dark");
// this is not working
forceUpdate();
}, [getColorTheme()]);
}
return (
<div
className={(darkMode ? "dark-mode-theme" : "")}
>
...
</div>
)
}