import { useLayoutEffect, useRef } from 'react'; /** Opens on the newest message and follows new ones, unless the reader has scrolled up to read back. */ export const useFollowNewest = (lastMessageId: string | undefined) => { const listRef = useRef(null); const atNewest = useRef(true); useLayoutEffect(() => { const list = listRef.current; if (list && atNewest.current) list.scrollTop = list.scrollHeight; }, [lastMessageId]); const onScroll = () => { const list = listRef.current; if (list) atNewest.current = list.scrollHeight - list.scrollTop - list.clientHeight <= 80; }; return { listRef, onScroll }; };