LearnFrenzy
Sign in Take a free test

React interview · Set 1 of 8

React Fundamentals and Hooks

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

UI as a function of state

Hold that idea and most React questions answer themselves: state changes, React re-runs the component, and reconciliation updates the DOM. Effects are the escape hatch to the outside world — use them sparingly.

  • RenderingReconciliation, props, state and keys.
  • HooksuseState, useEffect, useRef and custom hooks.
  • PitfallsStale state, missing cleanup and needless effects.

React interviews start with how rendering works and quickly move to hooks — especially useEffect, where most real bugs live. Answer with the mental model: a component is a function of props and state, and React re-runs it when they change.

1. How does React update the screen?

When state or props change, React calls your component again to get a new description of the UI. It compares the new tree with the previous one (reconciliation) and applies only the necessary DOM changes. Rendering is cheap; touching the DOM is what React minimises.


2. Props vs state?

Props are inputs passed from the parent and are read-only inside the component. State is data the component owns and changes over time with a setter, which triggers a re-render. If two components need the same state, lift it to their closest common parent.

function Counter({ step = 1 }) {                 // step: prop
  const [count, setCount] = useState(0);          // count: state
  return <button onClick={() => setCount(c => c + step)}>Count: {count}</button>;
}

3. Why use the updater function form of setState?

State updates are batched and applied on the next render, so count inside a handler is a snapshot. When the new value depends on the old one, pass a function so each update receives the latest value.

function addThree() {
  setCount(count + 1); setCount(count + 1); setCount(count + 1);   // +1 only
  setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); // +3
}

4. How does useEffect work, and when do you need cleanup?

useEffect synchronises your component with something outside React — a subscription, a timer, a non-React widget, a fetch. It runs after render; the dependency array decides when it re-runs. Return a cleanup function to undo the effect before the next run and on unmount.

useEffect(() => {
  const id = setInterval(() => setSeconds(s => s + 1), 1000);
  return () => clearInterval(id);            // cleanup prevents leaks and double timers
}, []);

5. When should you NOT use useEffect?

Do not use effects to compute values from props or state — compute them during render. Do not use them to respond to user events — put that logic in the event handler. Effects are for synchronising with external systems. Removing unnecessary effects removes a whole class of bugs.

// wrong: extra render and a stale moment
const [fullName, setFullName] = useState('');
useEffect(() => setFullName(`${first} ${last}`), [first, last]);

// right: derive during render
const fullName2 = `${first} ${last}`;

6. Why do lists need keys, and why not the index?

Keys tell React which item is which between renders so it can keep state and DOM nodes attached to the right item. Using the array index breaks when items are inserted, removed or reordered — inputs show the wrong values. Use a stable id from your data.

<ul>
  {todos.map(todo => <TodoItem key={todo.id} todo={todo} />)}
</ul>

7. What is useRef used for?

useRef holds a mutable value that survives renders without causing re-renders — a DOM node to focus, a timer id, or the previous value of a prop. Changing ref.current does not update the screen.

function SearchBox() {
  const inputRef = useRef(null);
  useEffect(() => { inputRef.current.focus(); }, []);
  return <input ref={inputRef} placeholder="Search topics" />;
}

8. Write a custom hook.

A custom hook is a function starting with use that combines other hooks so logic can be reused across components. Each component that calls it gets its own state.

function useFetch(url) {
  const [state, setState] = useState({ data: null, error: null, loading: true });
  useEffect(() => {
    const controller = new AbortController();
    fetch(url, { signal: controller.signal })
      .then(r => (r.ok ? r.json() : Promise.reject(new Error(r.status))))
      .then(data => setState({ data, error: null, loading: false }))
      .catch(error => { if (error.name !== 'AbortError') setState({ data: null, error, loading: false }); });
    return () => controller.abort();          // ignore stale responses
  }, [url]);
  return state;
}

Remember

Key points

  • Derive, do not sync

    Compute values during render instead of in effects.

  • Updater functions

    Use setX(prev => …) when the new value depends on the old.

  • Stable keys

    Ids, not array indexes.

  • Clean up effects

    Timers, subscriptions and in-flight requests.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What are the rules of hooks? Basic

    Call hooks only at the top level of a component or custom hook — not in loops, conditions or nested functions — so React can match them by call order.

  2. 2 Controlled vs uncontrolled inputs? Basic

    Controlled inputs take their value from state and update it on change; uncontrolled inputs keep their own DOM value, read with a ref or form data.

  3. 3 How do you share data deeply without prop drilling? Intermediate

    Context for rarely-changing values (theme, current user, locale), or a state library for frequently changing global state.

  4. 4 Why does my effect run in an infinite loop? Intermediate

    It sets state that is also a dependency, or a dependency is a new object/function every render. Move the object inside the effect, memoise it, or depend on primitive values.

  5. 5 What does useLayoutEffect do differently? Advanced

    It runs synchronously after DOM changes but before the browser paints — for measuring layout (tooltip positions) without flicker. Use it rarely; it blocks painting.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links