RA.
RA.

Reputation: 1029

How do I wait for child components to be "ready" with React hooks?

So I have a Page component that contains several Column components, each column contains different user-specific markup.

In the Page component I need to do some additional mutations (like the column overflow check, pushing columns content around, etc.). For this reason, I need a way to be notified after all Column components have mounted - also including implicit mutations have been made.

My first attempt was useEffect hook, however, it does get called before the Column component even receives it's ref.

// AppContext
const [columns, setColumns] = useState([]);

const Page = ({children}) => {
    useEffect({
       // This gets called before columns are available
    }, []);

    return (<div className="page">{children}</div>);
}

const View = () => {
    const {columns} = useContext(AppContext);

    return (
        <Page>
            {columns.map(c => <Column>{c}</Column>)}
        </Page>
    );
}

Upvotes: 3

Views: 3413

Answers (1)

AmerllicA
AmerllicA

Reputation: 32747

Actually, based on ReactJS docs there is a hook exactly like useEffect but it calls its callback after all DOM mutations, that name is useLayoutEffect:

The signature is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously before the browser has a chance to paint.

I prefer to use useEffect because based on Docs maybe using useLayoutEffect caused issues about render-blocking.

For your special case, you can use the useLayoutEffect.

Upvotes: 1

Related Questions