React Context API – Toggling Dark Mode the right way



Hey guys

In this video I show you how to effectively toggle dark mode in your react.js application. This involves solving the challenge of sharing data between multiple components in a component tree.

This sample application shows you how you should implement a react context to read a global dark mode setting, as well as how to change this value accordingly, making it affect the theme of your entire app. It also shows you how to use react hooks to implement such functionality, including creating your own custom hook.

We talk about how to create a context (using createContext), when to use it (for example to prevent prop drilling etc), and how each component in our component tree can use the context (via useContext hook). We also show how we should wrap such context specific code in a wrapper component (If you don’t know what wrapper components are, I explain them in this video. https://www.youtube.com/watch?v=wKhpNWIe8qo), and also how to create a custom react hook to illustrate a common pattern for using contexts.

The code for this video can be found at https://github.com/lyraddigital/react-dark-mode with:-

– The main being the final outcome of the video
– The startup branch being the code at the start of the video. (if you wish to follow along)

Here is a breakdown of what this video contains.

00:00 Introduction
00:20 Starting Point
03:53 What is a component tree
05:13 Creating the context
06:36 Setting the context value
07:38 Using / Consuming the context
11:18 Refactoring our context
12:12 Moving the context to it’s own file
13:26 Creating a custom hook
15:41 Creating our wrapper component
17:57 Conclusion
19:35 Outro

source