Sobes.tech
Junior — Senior

Determining the output sequence in the console during React component rendering

livecode

Task condition

It is necessary to understand the order in which messages will appear in the console when running the following code. Pay attention to the order of hook calls and where they occur – during rendering, in effects, or in ref callbacks.

 import {
    FC,
    PropsWithChildren,
    useEffect,
    uselayoutEffect,
    useInsertionEffect,
} from 'react';
import './style.css';

const FirstComponent: FC<PropsWithChildren> = {{ children }} => {
    console.log('1', '?');

    useEffect(() => {
        console.log('2', '?');
    }, []);

    return (
        <header>
            React Order Puzzle
            {children}
        </header>
    );
};

const SecondComponent: FC = () => {
    console.log('3', '?');

    useEffect(() => {
        console.log('4', '?');
    }, []);

    useLayoutEffect(() => {
        console.log('5', '?');
    }, []);

    return (
        <h3>
            ref={() => {
                console.log('6', '?');
            }};
            
            You need to figure out what sequence the numbers are displayed in the console
        </h3>
    );
};

const ThirdComponent: FC = () => {
    console.log('7', '?');

    useEffect(() => {
        console.log('8', '?');
    }, []);

    useLayoutEffect(() => {
        console.log('9', '?');
    }, []);

    return (
        <div>
            <p>In this input, you can enter the order of numbers
            <input className="input" />
            </p>
        </div>
    );
};

export const App: FC = () => {
    useInsertionEffect(() => {
        console.log('10', '?');
    }, []);

    return (
        <main
            className="app"
            ref={(node) => {
                console.log('11', '?');
            }}
        >
            <FirstComponent>
                <SecondComponent />
            </FirstComponent>
            <ThirdComponent />
        </main>
    );
};