Sharing component logic between components in React has been challenging. It's the problem where we have multiple components with different UIs but want to have the same stateful logic. Class mixins, higher-order components, and render props are all ways we've tried to solve this problem. Now, creating custom Hooks lets you extract component logic into reusable functions. A feature that is not available for class components.
🏅 The goal of this step is to learn how to combine hooks to create custom hooks.
Help! I didn't finish the previous step! 🚨
If you didn't successfully complete the previous step, that's okay! The steps are meant to push you. 😄
However, you may find yourself in a position where you app is not compiling, and it's preventing you from working on this step. No problem! Stash your changes in a new terminal window, and you should be good to continue:
git stash push -m "In-progress Step 3 exercises"
Your app should automatically reset and you should be able to continue on with the current step.
- Sharing component logic by creating custom hooks
- How to create async custom hooks
In Page.js
, extract the results
state and the useEffect()
calling the Giphy API into a useGiphy
custom hook in useGiphy.js
.
(If at any point you get stuck, you can take a peek at the answers)
After you're done with the exercise and before jumping to the next step, please fill out the elaboration & feedback form. It will help seal in what you've learned.
Create a useTheme
hook that will read the ThemeContext
and return the foreground
& background
theme values for the current theme:
/**
* Custom hook that reads theme context and returns
* the theme data
* @returns {{ background: string, foreground: string }}
*/
const useTheme = () => {
// return the background & foreground data for
// current theme
}
You should be able to use it in Page.js
, SearchForm.js
& ResultItem.js
.
Create a useDarkMode
hook that will extract the logic in App.js
for maintaining the dark mode setting as well as initializing to the user's dark mode preference.
/**
* Custom hook that will maintain the dark mode choice,
* initializing to the user's dark mode preference
* @param {boolean} defaultIsDarkMode The default value dark mode setting
* @returns {[boolean, (isDarkMode: boolean) => void]}
*/
const useDarkMode = (defaultIsDarkMode = false) => {
// return the dark mode setting + a function to update the setting
}
🔑 HINT: useDarkMode
maintains a boolean
while the theme
passed down in context is a string
(light
or dark
). You will need to derive both theme
& setTheme
from the values returned from useDarkMode
.
- Building Your Own Hooks
- React Hooks: Custom Hooks 📺
- Writing a Custom Hook:
useEventListener
📺 react-use
- From Mixins to Custom Hooks: A history of sharing in React 📺
useDebugValue
API ReferenceuseCallback
API Reference- Render props
- Higher-order components
Go to End.