Core Hooks

Preview — 3 of 10 questions

What is the initial value of count and when is useState(0) evaluated?

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}
Acount starts at undefined — 0 is the default fallback
Bcount starts at 0; the 0 argument to useState is only used on the first render — subsequent renders use the stored state value
CuseState(0) is called on every render and resets count to 0 each time
Dcount starts at null because React doesn't accept primitive initial values

What is the difference between these three useEffect calls?

javascript
useEffect(() => { /* A */ });
useEffect(() => { /* B */ }, []);
useEffect(() => { /* C */ }, [count]);
AA, B, and C all run after every render — the dependency array is cosmetic
BB runs every second; C runs when component unmounts
CA runs once on mount; B runs after every render; C runs only when count changes
DA runs after every render; B runs only once (on mount); C runs after mount AND every time count changes

What does the cleanup function in useEffect do?

javascript
useEffect(() => {
  const timer = setInterval(() => {
    setTime(new Date());
  }, 1000);

  return () => {
    clearInterval(timer); // cleanup
  };
}, []);
AThe returned function runs when the component unmounts AND before the effect runs again (if dependencies change) — it prevents memory leaks and stale callbacks
BCleanup runs before the component renders for the first time
CCleanup only runs when the component unmounts — not between re-runs of the effect
DReturning a function from useEffect is a syntax error

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.