Public
Edited
Jun 23, 2022
6 stars
Insert cell
Insert cell
Insert cell
Insert cell
function useMediaQuery(mediaQueryString) {
/*
* Initialize 'matches' with 'false' on the server, and with the correct
* value in the browser.
*/
const [matches, setMatches] = useState(
typeof window === 'undefined'
? false
: !!window.matchMedia(mediaQueryString).matches
)

/*
* Continuously monitor the media query and update 'matches' accordingly.
*/
useEffect(() => {
const mediaQueryList = window.matchMedia(mediaQueryString)
const listener = () => setMatches(!!mediaQueryList.matches)
mediaQueryList.addListener(listener)
return () => mediaQueryList.removeListener(listener)
}, [mediaQueryString])

return matches
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function useBetterMediaQuery(mediaQueryString) {
const [matches, setMatches] = useState(null)

useEffect(() => {
const mediaQueryList = window.matchMedia(mediaQueryString)
const listener = () => setMatches(!!mediaQueryList.matches)
mediaQueryList.addListener(listener)

// Call the listener() function immediately to set the local
// state as soon as possible.
listener()
return () => {
mediaQueryList.removeListener(listener)
}
}, [mediaQueryString])

return matches
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
import { useState, useEffect, useCallback, useRef, component, jsx, render } from "@j-f1/react"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more