Creating a custom Theme Hook
After getting a good grasp on the concept of Hooks by learning about the built-in React Hooks, community Hooks, as well as the rules of Hooks, we are now going to build our own Hooks.
In Chapter 5, Implementing React Contexts, we introduced a ThemeContext
to style blog posts in our app. We used a Context Hook to access the ThemeContext
in many components. Functionality that is used across multiple components is usually a good opportunity for a custom Hook. As you might have noticed, we often do the following:
import { ThemeContext } from '@/contexts/ThemeContext.js'
export default function SomeComponent () {
const theme = useContext(ThemeContext)
// …
We could abstract this functionality into a useTheme
Hook, which will get the theme
object from the ThemeContext
.
Usually, it makes the most sense to first write the component, and then later extract a custom Hook from it if we notice that we use similar code across...