Creating a dark mode for your React app with useContext()

"white" : "black"};`export default props => { const { darkMode } = useContext(DarkModeContext); return ( <Layout darkMode={darkMode}> {props.

children} </Layout>)}Now, the Layout is consuming the context from the Provider we made in our ContextWrapper component.

Not only the Layout, but any component that is a child (or grandchild or great-grandchild, etc.

) of the ContextWrapper component will be able to subscribe directly to the Provider, with no need to pass the data through each parent component.

Sweet!Updating the ContextThe cool thing about this set up is that now all of those Consumers also have access to the toggleDarkMode function we implemented in the ContextWrapper component.

So we can create a toggle button like this:** /components/DarkModeSwitch.

js **import { useContext } from "react";import styled from "styled-components";import { DarkModeContext } from ".

/hooks/DarkModeContext";export default () => { const { darkMode, toggleDarkMode } = useContext(DarkModeContext); return ( <button onClick={toggleDarkMode}> click for {darkMode ? "light mode" : "dark mode"} </button> );};And render it anywhere in the component tree as long is it is a descendent of the ContextWrapper component (our Provider).

That’s allIf you want to see mine in action, you can see the (rough) draft of my portfolio page here.

Please don’t judge me too hard! It is a work in progress :)You can also see the code for the whole project in this repo if you want to see it all put together.

.

. More details

Leave a Reply