Skip to content

Instantly share code, notes, and snippets.

@jide
Last active November 16, 2023 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jide/4e8a0dfe1bdec2398e60fe37d08fbb34 to your computer and use it in GitHub Desktop.
Save jide/4e8a0dfe1bdec2398e60fe37d08fbb34 to your computer and use it in GitHub Desktop.
Prevent grid layout overlap inside flex containers.
import { useState, useLayoutEffect, useCallback } from "react";
import { flushSync } from "react-dom";
const useDynamicMinHeight = (ref) => {
const [minHeight, setMinHeight] = useState(0);
const updateMinHeight = useCallback(() => {
if (ref.current) {
flushSync(() => {
setMinHeight(0);
});
setMinHeight(ref.current.scrollHeight);
}
}, [ref]);
useLayoutEffect(() => {
// Update minHeight on mount and whenever the ref changes
updateMinHeight();
// Handle window resize
window.addEventListener("resize", updateMinHeight);
// Cleanup
return () => {
window.removeEventListener("resize", updateMinHeight);
};
}, [updateMinHeight]);
return minHeight;
};
export default useDynamicMinHeight;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment