How to Create a useBreakpoint Hook in React
To create a custom useBreakpoint
hook in React, import useState
and useEffect
from React, create a resize
function for updating the breakpoint, and add a resize
event to the window
inside the useEffect
:
import { useState, useEffect } from 'react'
const useBreakpoint = () => {
const [breakpoint, setBreakpoint] = useState(1200)
const resize = () => {
setBreakpoint(window.innerWidth)
}
useEffect(() => {
window.addEventListener('resize', resize)
return () => {
window.removeEventListener('resize', resize)
}
}, [])
return breakpoint
}
This hook will return the breakpoint
variable which is updated every time the window is resized. You can either assign the width of the window to this variable or even use a map to assign a string to it based on some screen dimensions.
For example, return x-small
if the width is less than 600, and so on.
Don't forget to return a function from the useEffect
to remove the event listener when the component unmounts. Note that this event will likely fire more than you actually need it. To make it more performant, you can also wrap the event into a debounce function. If you would like to see it in action, give it a try on Codesandbox:
If you are interested in reading more about React hooks, see more examples for custom hooks or just learn about the basics, make sure to check out the article below.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: