React Hook - useLayoutEffect

useLayoutEffect is a React Hook that's mostly used in the position of object in the Dom without flicking.

It is similar to useEffect hook. Both hooks are similar in structure and function but the difference between them is that the previous(useLayoutEffect) is executed before the Dom gets rendered while the latter(useEffect) is executed after Dom rendering.

How To Use

useLayoutEffect, like the other `React Hooks` should :

  1. Be declared at the top level of component

  2. Should not be called inside loops or conditions in a function

useLayoutEffect hook is one of the React hook that many people don't know how and when to use. As a hook that gets fired before browser painting, the most common use case is that : it is used to set the actual position of data to the DOM before the page is rendered.

useEffect can as well be used for that same purpose but the limitation with useEffect is that it causes flicking of object positioning (sets the data as it is in the markup before running the function that sets the actual position defined for the data) when the page is rendered.

Practical Guide On How To Use useLayoutEffect

`

import React, { useLayoutEffect, useRef, useState } from 'react';

const App = () => {
  const [show, setShow] = useState(false);
  const [top, setTop] = useState(0);
  const popup = useRef();
  const button = useRef();
 useLayoutEffect(() => {
    if (popup.current === null || button.current === null) return;

    const { bottom } = button.current.getBoundingClientRect();
    setTop(bottom + 35);

  }, [show]);
  return (
    <>
      <button onClick={() => setShow((prev) => !prev)} ref={button}>
        show
      </button>

      {/* <div>{count}</div> */}
      {show ? (
        <div
          style={{ position: 'absolute', top: `${top}px` }}
          ref={popup}
          className="div"
        >
          {' '}
          This is popup
        </div>
      ) : null}
    </>
  );
};
export default App;

NOTE: useLayoutEffect is a synchronous hook. It runs before React updates it's state in the browser.

It is also important to know that too much use of this hook (useLayoutEffect) can slow down your app because it has to be executed, before the browser is painted.