How to Create a useBreakpoint Hook in React

How to Create a useBreakpoint Hook in React

Ferenc Almasi β€’ 2022 January 12 β€’ Read time 2 min read
  • twitter
  • facebook
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:

Copied to clipboard! Playground
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:

Try the hook on codesandbox
How to Create a useBreakpoint Hook in React
If you would like to see more Webtips, follow @flowforfrank

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.

All You Need to Know About React Hooks
  • twitter
  • facebook
React
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.