In many components, we use the ThemeContext to style our blog app. Functionality that is used across multiple components is usually a good opportunity for creating a custom Hook. As you might have noticed, we often do the following:
import { ThemeContext } from '../contexts'
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.
Let's start creating a custom useTheme Hook:
- Create a new src/hooks/ directory, which is where we are going to put our custom Hooks.
- Create a new src/hooks/useTheme.js file.
- In this newly created file, we first import the useContext Hook and the ThemeContext as follows:
import { useContext } from 'react'
import { ThemeContext } from '../contexts'
- Next, we export a new function called useTheme; this will be our custom Hook. Remember, Hooks are just functions prefixed with the use keyword:
export default function useTheme () {
- In our custom Hook, we can now use the essential Hooks provided by React to build our own Hook. In our case, we simply return the useContext Hook:
return useContext(ThemeContext)
}
As we can see, custom Hooks can be quite simple. In this case, the custom Hook only returns a Context Hook with the ThemeContext passed to it. Nevertheless, this makes our code more concise and easier to change later. Furthermore, by using a useTheme Hook, it is clear that we want to access the theme, which means our code will be easier to read and reason about.