React Hooks Fundamentals Quiz
Six drills on the core React hooks: useState, useEffect, useReducer, useCallback, useMemo, and writing custom hooks. Good for tightening mid-level interview answers.
356 views
9
What does useEffect(fn, []) do, and how is it different from useEffect(fn) with no dependency array? Answer in 2 to 3 sentences.
Write a Counter component using useState. Include increment, decrement, and a reset button that returns the count to the initial value.
Implement a useLocalStorage(key, initial) custom hook that mirrors useState but persists writes to window.localStorage. Handle the SSR case where window is undefined.
Refactor this counter from useState to useReducer. Why is useReducer a better fit once a component's state has multiple interrelated transitions?
import { useState } from 'react';
export function ToggleCounter() {
const [count, setCount] = useState(0);
const [enabled, setEnabled] = useState(true);
return (
<div>
<button disabled={!enabled} onClick={() => setCount((c) => c + 1)}>+</button>
<button onClick={() => setEnabled((e) => !e)}>{enabled ? 'lock' : 'unlock'}</button>
<span>{count}</span>
</div>
);
}The list below re-renders all 1000 rows whenever the parent rerenders, even though only query changes. Use useMemo and useCallback to fix it. Where is each hook actually doing work?
import { useState } from 'react';
export function Search({ items }) {
const [query, setQuery] = useState('');
const filtered = items.filter((i) => i.name.includes(query));
const onSelect = (id) => console.log('selected', id);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<Rows rows={filtered} onSelect={onSelect} />
</div>
);
}What are the two Rules of Hooks and why does React enforce them? Be specific about what breaks when you violate them.
