Consider this React custom hook that tracks window width. What will the component display after resizing the window to 800 pixels wide?
import React, { useState, useEffect } from 'react'; function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { function handleResize() { setWidth(window.innerWidth); } window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return width; } export default function WidthDisplay() { const width = useWindowWidth(); return <div>Window width is {width}</div>; }
Think about how the hook updates state on window resize events.
The custom hook listens for window resize events and updates the width state accordingly. After resizing to 800 pixels, the component shows "Window width is 800".
Which of the following custom hook definitions is syntactically correct and follows React hook naming conventions?
Custom hooks must start with 'use' and use camelCase.
React requires custom hooks to start with 'use' and be camelCase. Option C follows this naming and syntax correctly.
Examine this custom hook. Why does the component using it keep re-rendering infinitely?
import { useState, useEffect } from 'react'; function useCounter() { const [count, setCount] = useState(0); useEffect(() => { setCount(count + 1); }, [count]); return count; }
Think about what happens when state changes inside useEffect with that dependency.
The useEffect depends on 'count' and updates 'count' inside it. Each update triggers useEffect again, causing an infinite loop.
Which of the following is a best practice when writing custom React hooks?
Think about what custom hooks are designed to do in React.
Custom hooks start with 'use' and can contain stateful logic and side effects to share behavior across components.
Given this custom hook and component, what is the final value of count displayed?
import React, { useState, useEffect } from 'react'; function useDelayedIncrement(initial) { const [count, setCount] = useState(initial); useEffect(() => { const id = setTimeout(() => { setCount(c => c + 1); }, 1000); return () => clearTimeout(id); }, [count]); return count; } export default function Counter() { const count = useDelayedIncrement(0); return <div>{count}</div>; }
Consider how the effect depends on count and triggers a timeout each time.
The effect runs every time count changes, scheduling a new increment after 1 second. This causes count to increase by 1 every second indefinitely.