Katkat

Explain React classes, lifecycle, and hooks

SnowflakeFrontend Engineer · Technical Screen

Last updated

This question assesses the evolution of React component patterns, specifically focusing on the transition from class-based lifecycles to functional hooks, and the management of stateful side effects.

The Transition from Classes to Hooks

Modern React development has largely moved away from Class components in favor of Functional components using Hooks. To demonstrate your understanding of this evolution, address the following scenarios:

1. The Class Lifecycle

In a Class component, how would you implement a mechanism to fetch user data when the component mounts and clear a timer or abort the request when the component unmounts? Identify the specific lifecycle methods required.

2. The Functional Equivalent

Rewrite the logic described above using a Functional component and the useEffect hook. Explain how the dependency array in useEffect dictates when the effect runs and how the cleanup function works.

3. Practical Reasoning

Consider the following component snippet:

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      console.log("Count is: " + count);
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return {count};
}
  • Identify the bug in the code above regarding stale closures.
  • Explain why the count value logged and used inside setInterval does not update as expected.
  • Propose the correct fix for this behavior.

4. Code Reuse

Compare and contrast the strategies for sharing stateful logic between components in Class components (e.g., Higher-Order Components or Render Props) versus the approach used with Custom Hooks. Why are Custom Hooks generally preferred in modern React?

Hints

Hint 1

Recall that componentDidMount and componentWillUnmount are the primary class lifecycle hooks for setup and teardown.

Hint 2

Remember that an empty dependency array in useEffect mimics the behavior of componentDidMount, but only if the cleanup function is also handled correctly.

Hint 3

For the stale closure issue, think about how functional updates in setCount (e.g., setCount(c => c + 1)) or the useRef hook can help capture the latest state.

Follow-up questions

  • How does the React rendering cycle differ when using 'useMemo' versus 'useCallback', and when should you avoid using them?
  • Can you explain the 'Rules of Hooks' and why they are necessary for React to maintain state consistency across renders?
  • In what specific scenarios would you still consider using a Class component over a Functional component in a professional codebase?