Blogify

Blogify

react hooksreact

15 Weird and Tricky React Hooks Interview Questions with Detailed Answers

Volodymyr

Volodymyr

Post

1. What is the difference between useEffect and useLayoutEffect? When would you use one over the other?

Answer:

• useEffect runs asynchronously after the render is committed to the screen, while useLayoutEffect runs synchronously after all DOM mutations but before the browser paints.

• Use useEffect for side effects that don’t require immediate execution (e.g., data fetching, subscriptions).

• Use useLayoutEffect for operations that need to happen before the user sees the result (e.g., measurements, modifying DOM elements).

Example:

useEffect(() => { console.log('useEffect'); // Runs after paint }); useLayoutEffect(() => { console.log('useLayoutEffect'); // Runs before paint });

2. Can you explain how to avoid an infinite loop with useEffect?

Answer: An infinite loop occurs when useEffect depends on a value that updates inside it, causing the effect to re-run continuously.

Example (Incorrect):

useEffect(() => { setCount(count + 1); // Updating `count` in useEffect }, [count]); // Triggers re-renders infinitely

Solution: Ensure that dependencies don’t cause state changes within the effect, or use a conditional check.

3. What are stale closures in useEffect? How can you prevent them?