use of useLayoutEffect hooks in React native?
What is use useLayoutEffect in React native
Before we go to know the use of useLayoutEffect in react native first we know about the useLayoutEffect
What is useLayoutEffect
useLayoutEffect
is a version of useEffect
that fires before the browser repaints the screen.
OR
useLayoutEffect
hook happens synchronously before the real dom is rendered.
Use of useLayoutEffect
useLayoutEffect(function, dependencies?)
useLayoutEffect take two parameters :-
1. function – The function where you can implement your logic or any functional things to perform any update on state and any other things.
2. dependency (optional) – The list of all values referenced inside of the setup
code. Values like props, state, and all the variables and functions declared directly inside your component body. The list of dependencies number of items and be written inline like [dep1, dep2, dep3]
. React will compare each dependency with its previous value . If dependency value is change then useEffect will re-render.
Measuring layout before the browser re-render the screen
Most components in react native don’t need to know their position and size or where to render on the screen. Then the browser calculates their layout (position and size) and re-render the screen.
Sometimes, camponent dont know the height or size where to render. Imagine a popup that appears next to some element on hover. If there’s enough space, the popup will appear above the element, but if it doesn’t fit, it should appear below. In order to render the popup at the right position then you need to know its height where its fit on the top
function headerHeight() {
const ref = useRef(null);
const [headerHeight, setHeaderHeight] = useState(0); // You don't know real height yet
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setHeaderHeight(height); // Re-render now that you know the real height
}, []);
// ...use headerHeight in the rendering logic below...
}