Skip to content

Instantly share code, notes, and snippets.

@ruucm
Created April 18, 2021 09:12
Show Gist options
  • Save ruucm/2d577cc40d6220342cbaffb92b60ab54 to your computer and use it in GitHub Desktop.
Save ruucm/2d577cc40d6220342cbaffb92b60ab54 to your computer and use it in GitHub Desktop.
A simple custom hook to get element's ref.
/**
* A simple custom hook to get element's ref.
* @example
* import { useElement } from "./useElement";
*
* export function Test() {
* const [ref, element] = useElement();
*
* return (
* <div ref={ref}>Test {element && element.getBoundingClientRect().width}</div>
* );
* }
*/
import { useState, useCallback } from "react";
export function useElement() {
const [element, setElement] = useState(null);
const ref = useCallback((node) => {
setElement(node);
}, []);
return [ref, element];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment