Skip to content

Instantly share code, notes, and snippets.

@tortillaj
Created January 28, 2019 20:32
Show Gist options
  • Save tortillaj/0c6bd161e97230e1ff9c1a5650919f4e to your computer and use it in GitHub Desktop.
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
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
@tortillaj
Copy link
Author

Usage:

  • Initialize with 12 columns
  • Then, small screens have 12 columns, medium screens have 6, and large screens have 3
const count = useColumnCount(12, [{ width: 1000, count: 3}, { width: 500: count: 6 }, { width: 0, count: 12 }]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment