Custom Hooks Examples 🎯

beginner
16 min

Custom Hooks Examples 🎯

Welcome to our deep dive into Custom Hooks in React JS! This tutorial is designed to guide both beginners and intermediate learners through the practical use of Custom Hooks, making your React components more reusable and maintainable.

What are Custom Hooks? 📝

Custom Hooks are a new addition to React, introduced in version 16.8, that help you reuse logic between hooks. They are functions that begin with the "use" prefix, just like the built-in hooks (useState, useEffect, etc.).

Why use Custom Hooks? 💡

Custom Hooks are a powerful tool that simplifies the process of managing complex state logic and side effects in your React components. They allow you to extract and reuse logic from multiple hooks, making your code cleaner, more modular, and easier to test.

Creating a Custom Hook ✅

Let's create a simple Custom Hook that manages the local storage of a theme.

javascript
import { useState, useEffect } from 'react'; const useTheme = () => { const [theme, setTheme] = useState(getInitialTheme()); useEffect(() => { localStorage.setItem('theme', theme); }, [theme]); const toggleTheme = () => { setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light')); }; const getInitialTheme = () => { const storedTheme = localStorage.getItem('theme'); return storedTheme || 'light'; }; return { theme, toggleTheme }; }; export default useTheme;

In the example above, we created a Custom Hook called useTheme that manages the theme of our application using local storage.

Using the Custom Hook ✅

Now, let's use our useTheme Custom Hook in a component.

javascript
import React from 'react'; import useTheme from './useTheme'; const App = () => { const { theme, toggleTheme } = useTheme(); return ( <div className={theme}> <h1>Welcome to our App!</h1> <button onClick={toggleTheme}>Toggle Theme</button> </div> ); }; export default App;

In the App component, we imported and used the useTheme Custom Hook to manage the theme and a button to toggle it.

Advanced Custom Hook Example 🎯

Let's create a Custom Hook called useWindowSize that retrieves the current window size and updates it whenever the window resizes.

javascript
import { useState, useEffect } from 'react'; const useWindowSize = () => { const [windowSize, setWindowSize] = useState({ width: window.innerWidth, height: window.innerHeight }); useEffect(() => { const handleResize = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight }); }; window.addEventListener('resize', handleResize); // Cleanup function to remove the event listener on component unmount return () => { window.removeEventListener('resize', handleResize); }; }, []); return windowSize; }; export default useWindowSize;

In this example, we created a useWindowSize Custom Hook that returns the current window size and updates it whenever the window resizes.

Using the Advanced Custom Hook ✅

Now, let's use the useWindowSize Custom Hook in a component to conditionally render content based on the window size.

javascript
import React from 'react'; import useWindowSize from './useWindowSize'; const App = () => { const { width } = useWindowSize(); return ( <div> {width > 768 ? ( <div> <h1>Desktop View</h1> <!-- Desktop-specific content --> </div> ) : ( <div> <h1>Mobile View</h1> <!-- Mobile-specific content --> </div> )} </div> ); }; export default App;

In the App component, we imported and used the useWindowSize Custom Hook to conditionally render content based on the window size.

Quick Quiz
Question 1 of 1

What is the purpose of the `useWindowSize` Custom Hook?

With these examples, you now have a solid understanding of creating and using Custom Hooks in your React projects. Happy coding! 🚀🌟