Created
January 28, 2019 20:32
-
-
Save tortillaj/0c6bd161e97230e1ff9c1a5650919f4e to your computer and use it in GitHub Desktop.
React hook for setting column counts based on window size, useful for css grid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect, useLayoutEffect } from 'react' | |
interface Point { | |
count: number; | |
width: number; | |
} | |
const throttle = (throttledFunction: Function, wait: number, context: void) : any => { | |
let timeoutId: any = null | |
let callbackArgs: any[] = [] | |
const later = () : void => { | |
throttledFunction.apply(context, callbackArgs) | |
timeoutId = null | |
} | |
return (...args: any[]) : void => { | |
if (!timeoutId) { | |
callbackArgs = args | |
timeoutId = setTimeout(later, wait) | |
} | |
} | |
} | |
const useColumnCount = (initialColumnCount: number, breakpoints: Point[]): number => { | |
const [columnCount, setColumnCount] = useState(initialColumnCount) | |
const updateColumnCount = throttle(() : any => { | |
const match = breakpoints.find((point) : boolean => window.innerWidth > point.width) | |
if (match && columnCount !== match.count) setColumnCount(match.count) | |
}, 250) | |
useEffect(() => { | |
window.addEventListener('resize', updateColumnCount) | |
return () => { | |
window.removeEventListener('resize', updateColumnCount) | |
} | |
}) | |
useLayoutEffect(() => { | |
updateColumnCount() | |
}) | |
return columnCount | |
} | |
export default useColumnCount |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: