Creating a useTheme Hook

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:

  1. Create a new src/hooks/ directory, which is where we are going to put our custom Hooks.
  2. Create a new src/hooks/useTheme.js file.
  3. In this newly created file, we first import the useContext Hook and the ThemeContext as follows:
import { useContext } from 'react'
import { ThemeContext } from '../contexts'
  1. 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 () {
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.59.231