Custom Hooks
1/5/2025
Custom Hooks
Custom Hooks let you extract component logic into reusable functions.
Creating a Custom Hook
jsx
import { useState, useEffect } from 'react'
function useWindowSize() {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight
})
useEffect(() => {
function handleResize() {
setSize({
width: window.innerWidth,
height: window.innerHeight
})
}
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [])
return size
}Using Custom Hook
jsx
function Component() {
const { width, height } = useWindowSize()
return <p>Window: {width} x {height}</p>
}useFetch Hook
jsx
function useFetch(url) {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false))
}, [url])
return { data, loading, error }
}
Monkey Knows Wiki