← Interview prep

React interview questions

Hooks, rendering, state, and React interview favorites.

150 questions · Page 2 of 8

Want the full pack? Interview packs · Mock interview · Mentora

Page 2 of 8

Questions 21–40 of 150 · 0 of 20 on this page marked learned

21.react-0021Easyfresher

What is the difference between props and state in React?

Props are inputs passed from a parent to a child. The child reads them and must not change them. State is data a component owns and can change over time, and changing it triggers a re-render. A value that comes from a parent is a prop. A value that the component itself must remember and update is state. Data flows down through props, and changes flow up through callback props.

Full answer

Think of a marksheet row. The student name and marks arrive from the page that holds the data. The row cannot change them, it only displays them. Those are props. Whether the row is expanded to show details is something the row itself remembers. That is state.

Props are read-only inputs. A parent writes them like attributes: <StudentRow name="Asha" marks={82} />. The child receives an object, usually destructured in the function signature. If a child needs the parent to change something, the parent passes a function as a prop, and the child calls it. This is how data flows down and events flow up.

State is private memory. It is created with useState, which returns the current value and a setter. Calling the setter schedules a re-render with the new value. State survives between renders, while ordinary local variables are recreated every time the function runs.

Both props and state can cause a component to re-render, and both are snapshots for one render. Neither may be changed directly: never write props.name = 'x' or count++ on state.

A common design question is whether a value should be state at all. If it can be calculated from props or other state, calculate it during render instead of storing a copy. For example, a full name from first and last name needs no state. Duplicated state drifts out of sync.

Another sign for choosing: if two components need the same state, move it to their nearest common parent and pass it down as props. That pattern is called lifting state up.

jsx
import { useState } from 'react';

function StudentRow({ name, marks }) {
  const [expanded, setExpanded] = useState(false);
  const grade = marks >= 75 ? 'A' : marks >= 50 ? 'B' : 'C'; // derived, not state

  return (
    <li>
      {name}
      <button onClick={() => setExpanded(!expanded)}>{expanded ? 'Hide' : 'Show'} details</button>
      {expanded && <span> Marks: {marks}, Grade: {grade}</span>}
    </li>
  );
}

export default function App() {
  return (
    <ul>
      <StudentRow name="Asha" marks={82} />
      <StudentRow name="Ravi" marks={47} />
    </ul>
  );
}

name and marks are props, expanded is state, and the grade is calculated during render. The check clicked both buttons. Rendered result: <ul><li>Asha<button>Hide details</button><span> Marks: 82, Grade: A</span></li><li>Ravi<button>Hide details</button><span> Marks: 47, Grade: C</span></li></ul>

Key points

  • Props come from the parent and are read-only. State is owned by the component and changes with a setter.
  • Changing state re-renders the component. A parent re-rendering with new props also re-renders the child.
  • Never mutate props or state directly.
  • Do not store values that can be derived from props or other state.
  • Children ask parents to change data by calling callback props.

Common mistakes

  • Trying to modify a prop inside the child.
  • Copying a prop into state "to edit it" and then missing later updates from the parent.
  • Storing derived values in state.
  • Mutating state objects directly instead of using the setter.

Follow-ups

  • What happens if you copy a prop into useState, and how do you avoid the problem?
  • How does a child tell its parent that something happened?
  • Where would you keep state that two sibling components both need?

Tips

  • Give a one-line definition for each and then a real example. Do not stop at "props are immutable".
  • Mention derived values. It shows design sense.
  • Use "owns" for state and "receives" for props.
22.react-0022Easyfresher

Why does calling setCount(count + 1) three times increase the count by only one, and how do you fix it?

Inside one render, count is a fixed snapshot. So setCount(count + 1) three times means setCount(1) three times, and the result is 1. React also batches the three calls into one re-render. To base each update on the latest queued value, pass an updater function: setCount((c) => c + 1). That adds 3.

Full answer

State in React is not a variable that changes in place. Each render receives its own snapshot of state. If count is 0 in this render, then every use of count in this render's event handler is 0, even after calling the setter.

Look at three calls of setCount(count + 1). They are evaluated to setCount(1) three times, because count is still 0. React queues those updates and processes them together after the handler finishes, so the final state is 1.

An updater function changes the story. setCount((c) => c + 1) does not say "set to this value", it says "take the latest value and return the next one". React queues the three functions and runs them in order: 0 becomes 1, then 2, then 3. Use this form whenever the new state depends on the previous state, and in timers, intervals and async callbacks that could hold an old snapshot.

React batches updates. Since React 18, batching is automatic everywhere, including setTimeout callbacks, promises and native event handlers, not only React events. Several setState calls in one handler lead to one re-render, which is good for performance. If you need to read the DOM straight after a state change, flushSync from react-dom forces a synchronous update, but it is rarely necessary.

Two more details. Calling the setter with the same value, compared with Object.is, lets React skip the re-render. And the value you read right after calling the setter is still the old one, so do not log it expecting the new value.

jsx
import { useState } from 'react';

export default function Counters() {
  const [direct, setDirect] = useState(0);
  const [updater, setUpdater] = useState(0);

  function addThree() {
    setDirect(direct + 1);
    setDirect(direct + 1);
    setDirect(direct + 1);

    setUpdater((n) => n + 1);
    setUpdater((n) => n + 1);
    setUpdater((n) => n + 1);
  }

  return (
    <div>
      <button onClick={addThree}>Add three times</button>
      <p>Direct value: {direct}</p>
      <p>Updater function: {updater}</p>
    </div>
  );
}

One click calls each setter three times. Rendered result after the click: <div><button>Add three times</button><p>Direct value: 1</p><p>Updater function: 3</p></div>

Key points

  • A render sees one fixed snapshot of state. Calling a setter does not change the variable in the current render.
  • Use setX((previous) => next) when the next value depends on the previous one.
  • Updates are batched into one re-render, including in timers and promises since React 18.
  • Same-value updates are skipped using Object.is.
  • flushSync forces an immediate update but is rarely needed.

Common mistakes

  • Expecting the state variable to hold the new value on the next line after the setter call.
  • Using a stale count inside setInterval or setTimeout instead of an updater function.
  • Believing batching only happens inside React event handlers. That was true before React 18.
  • Mutating an object in place and calling the setter with the same reference.

Follow-ups

  • How would you read the new state value right after setting it?
  • What changed about batching in React 18?
  • What happens when you call a setter with the same value?

Tips

  • Use the word "snapshot". It explains the behaviour in one step.
  • Trace the example with numbers. Interviewers like to see the arithmetic.
  • Mention automatic batching to show you know the 18 change.
23.react-0023Easyfresher

How does the useEffect dependency array work, and why is cleanup important?

useEffect runs after React has rendered and updated the screen. Its dependency array decides when it runs again: with no array it runs after every render, with an empty array it runs after the first render (and once more in StrictMode development), and with values it runs when any of them changed. The cleanup function returned from the effect runs before the next run and when the component unmounts, to undo what the effect started.

Full answer

useEffect is for work that connects a component to something outside React: the browser window, a timer, a subscription or a network service. It runs after the render has been committed, so it does not block painting.

The second argument controls when it runs. Without an array, the effect runs after every render. With [], React runs it after the first render only. With [a, b], it runs after the first render and again after any render where a or b changed, compared with Object.is.

The array should list every reactive value (props, state, and variables derived from them) that the effect reads. Leaving a value out does not make the effect smarter. It makes it read stale values. The eslint rule react-hooks/exhaustive-deps warns about this, and the answer is almost always to fix the code, not to disable the rule.

Cleanup is the function you return. React calls it before running the effect again and when the component unmounts. If the effect added an event listener, the cleanup removes it. If it started a timer, the cleanup clears it. Without cleanup, listeners pile up, memory leaks and old callbacks run with outdated data.

In development, StrictMode runs each effect, its cleanup, and the effect again once after mount. This is a test that your cleanup mirrors your setup. It does not happen in production.

Not everything belongs in an effect. A value calculated from props can be computed during render. Code that answers a user click belongs in the event handler. Effects are for synchronising.

The example tracks the window width. Open and close the listener once per mount, not per render.

jsx
import { useEffect, useState } from 'react';

function WindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }
    window.addEventListener('resize', handleResize);
    console.log('listener added');
    return () => {
      window.removeEventListener('resize', handleResize);
      console.log('listener removed');
    };
  }, []);

  return <p>Width: {width}</p>;
}

export default function App() {
  const [visible, setVisible] = useState(true);
  return (
    <div>
      <button onClick={() => setVisible(false)}>Hide</button>
      {visible && <WindowWidth />}
    </div>
  );
}

The check shrinks the window to 800 pixels, then clicks Hide, which unmounts WindowWidth and triggers the cleanup. Console output and markup (jsdom starts with a width of 1024): listener added after resize: <div><button>Hide</button><p>Width: 800</p></div> listener removed

Key points

  • The dependency array controls when the effect re-runs, based on Object.is comparison.
  • List every reactive value the effect reads. Stale closures are the cost of leaving one out.
  • Cleanup runs before the next effect run and on unmount.
  • StrictMode runs an extra setup-cleanup-setup cycle in development only.
  • Derived values and event reactions do not belong in effects.

Common mistakes

  • Leaving out dependencies and reading stale state inside the effect.
  • Forgetting cleanup, which adds a new listener on every mount.
  • Using an effect to compute a value that could be calculated during render.
  • Treating [] as "componentDidMount" and ignoring changing props.
  • Making an effect async directly, because an effect must return a cleanup function or nothing, not a promise.

Follow-ups

  • What happens if an object created in render is listed as a dependency?
  • How would you fetch data inside an effect and avoid setting state after unmount?
  • What is useEffectEvent for?

Tips

  • Describe the three array forms briefly, then spend your time on cleanup and stale values.
  • Mention StrictMode when asked "why does my effect run twice".
  • Say that effects synchronise with the outside, and name one concrete outside system.
24.react-0024Easyfresher

How do you render content conditionally and render lists in React, and what common bugs should you avoid?

Use JavaScript inside JSX: an if with early return, a ternary for either-or, and && for show-or-nothing. For lists, call map on an array and return an element for each item with a stable key. The common bug is {count && <Item />}, which renders the number 0 when count is zero, so compare explicitly with count > 0.

Full answer

JSX has no special if or for syntax. You use ordinary JavaScript expressions, and React renders whatever they produce.

Outside the return, you can use if and early returns: if (loading) return <Spinner />;. This keeps the main layout readable.

Inside JSX, use a ternary for two outcomes, isAdmin ? <AdminMenu /> : <UserMenu />, and && when there is nothing to show in the other case, hasError && <ErrorText />. null, undefined, true and false render nothing, which makes this work.

The trap is && with numbers. In {items.length && <List />}, an empty array gives 0, and React renders the number 0 on screen, because 0 is a valid thing to display. Write items.length > 0 && <List /> or use a ternary.

For lists, call map and return elements: students.map((s) => <li key={s.id}>{s.name}</li>). Every element needs a key that is stable and unique among siblings. Use an id from the data. Filter first and then map if only some items should appear. An empty list should show an explicit empty state, since a blank area looks broken.

Do not put long logic inside the JSX. Prepare the array in a variable above the return, or extract a small component. Readable components usually have a short return statement.

The component below shows a loading branch, an empty branch and a list.

jsx
const students = [
  { id: 1, name: 'Asha', marks: 82 },
  { id: 2, name: 'Ravi', marks: 47 },
  { id: 3, name: 'Meera', marks: 91 },
];

function ResultList({ rows, loading }) {
  if (loading) {
    return <p>Loading results...</p>;
  }

  const passed = rows.filter((row) => row.marks >= 50);

  return (
    <section>
      <h2>Passed students ({passed.length})</h2>
      {passed.length > 0 ? (
        <ul>
          {passed.map((row) => (
            <li key={row.id}>
              {row.name} scored {row.marks}
            </li>
          ))}
        </ul>
      ) : (
        <p>No one passed yet.</p>
      )}
    </section>
  );
}

export default function App() {
  return <ResultList rows={students} loading={false} />;
}

The component returns early while loading, filters before mapping, and shows an empty-state message when there is nothing to list. Rendered result: <section><h2>Passed students (2)</h2><ul><li>Asha scored 82</li><li>Meera scored 91</li></ul></section>

Key points

  • Use if with early return, a ternary or && for conditions. All are plain JavaScript expressions.
  • null, undefined, true and false render nothing, but 0 and empty strings may render.
  • Guard numeric conditions with a comparison such as length > 0.
  • Render lists with map and give each element a stable key.
  • Show a deliberate empty state instead of a blank area.

Common mistakes

  • Writing {count && <Item />} and seeing a stray 0 on screen.
  • Forgetting the key prop on the mapped element, or placing it on an inner element.
  • Mapping with forEach, which returns undefined and renders nothing.
  • Using nested ternaries that are hard to read, instead of early returns or small components.

Follow-ups

  • Why does an empty array render nothing but the number 0 renders as text?
  • How would you handle a very long list efficiently?
  • How would you show loading, error and empty states for fetched data?

Tips

  • Mention the 0 trap. It is a classic filter for real experience.
  • Keep JSX short. Say that you move logic into variables or components.
  • Always say "stable key" when talking about lists.
25.react-0025Easyfresher

How do you handle events in React, and what are the common mistakes with event handlers?

Pass a function to a camelCase prop such as onClick or onSubmit. React calls it with an event object that wraps the browser event. Pass the function itself, not the result of calling it. Use event.preventDefault() to stop a form from reloading the page, and an arrow function when the handler needs arguments. Handlers are the right place for code that responds to user actions.

Full answer

React events look like HTML events, with differences. Names are camelCase (onClick, onChange), and the value is a function, not a string: <button onClick={handleClick}>.

The first common mistake is calling the function. In this fence, the handler runs while rendering instead of on click (error on purpose):

jsx
function Row({ id, onDelete }) {
  return <button onClick={onDelete(id)}>Delete</button>;
}

onDelete(id) runs immediately during render and passes its result to onClick. The fix is a function that calls it later: onClick={() => onDelete(id)}. Without arguments, pass the name: onClick={handleClick}.

The handler receives a SyntheticEvent, React's wrapper that behaves the same in all browsers. It has the usual methods: preventDefault() to cancel default behaviour, such as a form submit reloading the page, and stopPropagation() to stop the event bubbling to parents. event.target is the element that triggered the event. event.currentTarget is the element the handler is attached to. Since React 17 events are attached to the root container, and the old event pooling is gone, so you can read the event after an await.

Handlers can update state, call APIs and navigate. Do not use an effect for logic that exists only because the user clicked, since the handler already knows which action happened.

Some events bubble in surprising ways. A click on a button inside a clickable card runs both handlers. Use stopPropagation on the inner one when that is not wanted.

The form below stops the default submit, reads the typed value from state and passes an id to a handler.

jsx
import { useState } from 'react';

export default function SearchForm() {
  const [query, setQuery] = useState('');
  const [searches, setSearches] = useState([]); // items look like { id, text }

  function handleSubmit(event) {
    event.preventDefault();
    console.log('submitted ' + query);
    setSearches((list) => [...list, { id: list.length ? list[list.length - 1].id + 1 : 1, text: query }]);
    setQuery('');
  }

  function handleRemove(id) {
    setSearches((list) => list.filter((item) => item.id !== id));
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <button type="submit">Search</button>
      <ul>
        {searches.map((item) => (
          <li key={item.id}>
            {item.text} <button type="button" onClick={() => handleRemove(item.id)}>Remove</button>
          </li>
        ))}
      </ul>
    </form>
  );
}

The check typed a name and pressed Search. The page did not reload, the value was logged, and it was added to the list. Output of the run: submitted Asha Rendered result: <form><input value=""><button type="submit">Search</button><ul><li>Asha <button type="button">Remove</button></li></ul></form>

Key points

  • Event props are camelCase and take a function.
  • Pass the function or an arrow wrapper. Do not call it in JSX.
  • preventDefault cancels default browser behaviour, and stopPropagation stops bubbling.
  • event.target is the origin element and event.currentTarget is the element holding the handler.
  • Logic caused by a user action belongs in the handler, not in an effect.

Common mistakes

  • Writing onClick={handler()} and running the handler during render.
  • Forgetting event.preventDefault() on a form submit.
  • Confusing event.target with event.currentTarget when a child element is clicked.
  • Using a string handler like onclick="..." from HTML.
  • Calling a setter in the render body instead of in a handler.

Follow-ups

  • What is event delegation in React, and where are listeners attached?
  • How do you stop a click in a child from triggering the parent handler?
  • When should you add a native event listener instead of a React prop?

Tips

  • Mention the "do not call it" trap first, because it appears in many screening tests.
  • Know target versus currentTarget. It is a standard follow-up.
  • Say that handlers, not effects, are the place for reacting to user actions.
26.react-0026Easyfresher

What is the virtual DOM, and how does React's reconciliation decide what to update?

When state changes, React calls your components again to produce a new tree of plain objects describing the UI, often called the virtual DOM. It compares the new tree with the previous one and works out the smallest set of changes. Then it applies only those changes to the real DOM. Elements of the same type at the same position are updated in place, and a different type is replaced, which resets state below it.

Full answer

Updating the real DOM directly is slow when done carelessly, and hand-written update code is error-prone. React lets you describe the whole UI for the current state. It then handles the changes.

Every render produces React elements, which are lightweight objects. The collection of these elements is the "virtual DOM". It is a description, not a copy of the browser's DOM. React keeps the previous tree, builds the next tree, and compares them. This comparison step is called reconciliation, and the engine behind it is called Fiber.

A full tree comparison would be expensive, so React uses two assumptions. First, if two elements have different types (a div becomes a section, or one component becomes another), React tears down the old subtree and builds the new one. All state in the old subtree is lost. Second, in a list, keys identify items, so React can match elements that moved. Without keys, matching is by position.

For elements of the same type, React keeps the same DOM node and updates only the changed attributes and children. That is why typing in an input does not recreate the input.

React finishes with a commit phase, which applies the collected changes to the DOM in one go, and then runs layout effects and effects. The render phase can be paused or restarted in concurrent mode, while the commit phase cannot.

Saying "the virtual DOM is faster than the DOM" is a weak claim. It is a tool that makes declarative code affordable. The code below shows the DOM node being reused for a text change and replaced for a tag change.

jsx
import { useEffect, useRef, useState } from 'react';

export default function Demo() {
  const [title, setTitle] = useState('Marks');
  const [asSection, setAsSection] = useState(false);
  const nodeRef = useRef(null);
  const previous = useRef(null);

  useEffect(() => {
    if (previous.current !== null) {
      console.log('same DOM node reused: ' + (previous.current === nodeRef.current));
    }
    previous.current = nodeRef.current;
  });

  return (
    <div>
      <button onClick={() => setTitle('Results')}>Change text</button>
      <button onClick={() => setAsSection(true)}>Switch tag</button>
      {asSection ? (
        <section ref={nodeRef}>{title}</section>
      ) : (
        <div ref={nodeRef}>{title}</div>
      )}
    </div>
  );
}

The first click changes only the text, so React updates the existing node. The second click changes the element type from div to section, so React replaces the node. Output of the run: same DOM node reused: true same DOM node reused: false

Key points

  • The virtual DOM is a tree of lightweight elements describing the UI. It is not the real DOM.
  • Reconciliation compares the new tree with the previous one and produces a minimal set of changes.
  • Same type at the same position means update in place. A different type means replace and reset state.
  • Keys let React match list items that move.
  • The commit phase applies changes to the DOM in one step.

Common mistakes

  • Saying the virtual DOM is a copy of the real DOM.
  • Claiming the virtual DOM is always faster than direct DOM updates.
  • Defining components inside other components, which gives a new type on every render and remounts them.
  • Forgetting that a different element type resets state below it.

Follow-ups

  • Why does a component defined inside another component lose its state on each render?
  • How do keys change the comparison for lists?
  • What is the difference between the render phase and the commit phase?

Tips

  • Avoid the "virtual DOM is fast" slogan. Say what it enables: describe UI declaratively, update minimally.
  • State the two heuristics (type and key). They show you know how it works.
  • Use "render phase" and "commit phase" to show structure.
27.react-0027Easyfresher

What is the children prop, what are fragments, and how does composition replace inheritance in React?

children is a special prop that holds whatever you put between a component's opening and closing tags, so a component can wrap content it does not know in advance. A fragment groups several elements without adding an extra DOM node. Composition means building bigger components by combining smaller ones with children and props, and React recommends it instead of class inheritance for sharing UI.

Full answer

A layout component, such as a Card, should not need to know what goes inside it. React solves this with the children prop. <Card title="Marks"><p>82 out of 100</p></Card> passes the paragraph as props.children. Card places it with {children}. Any content works: text, elements, arrays, even functions if you design for it.

A component must return a single value, but you often want two siblings, such as a heading and a paragraph. Wrapping them in a div adds an unneeded node, which can break CSS layouts like tables and grids. A fragment, written <>...</>, groups them with no output. Use the long form <Fragment key={id}> when a key is needed, for instance when each list item produces a term and a description.

Composition is how React reuses UI. Instead of making SpecialButton extends Button, you write a Button that accepts props and children, and wrap or configure it. You can also pass elements through named props, such as header and footer, which works as slots for more complex layouts. Composition keeps components small, predictable and easy to test, and it avoids prop drilling.

Some points to remember. children can be changed in structure using the Children utilities, but this is rare and fragile, so prefer explicit props. Passing JSX as children creates new elements on each render of the parent, which matters for memo. And a fragment with no key is fine in static positions.

The glossary component in the code uses all three ideas.

jsx
import { Fragment } from 'react';

function Card({ title, children, footer }) {
  return (
    <section>
      <h2>{title}</h2>
      <div>{children}</div>
      <footer>{footer}</footer>
    </section>
  );
}

const terms = [
  { id: 'props', name: 'Props', meaning: 'Inputs passed from a parent.' },
  { id: 'state', name: 'State', meaning: 'Memory owned by a component.' },
];

export default function Glossary() {
  return (
    <Card title="React glossary" footer={<small>Updated weekly</small>}>
      <dl>
        {terms.map((term) => (
          <Fragment key={term.id}>
            <dt>{term.name}</dt>
            <dd>{term.meaning}</dd>
          </Fragment>
        ))}
      </dl>
    </Card>
  );
}

Card does not know what it wraps. A keyed Fragment lets each term produce two siblings (dt and dd) inside the dl element without an extra wrapper. Rendered result: <section><h2>React glossary</h2><div><dl><dt>Props</dt><dd>Inputs passed from a parent.</dd><dt>State</dt><dd>Memory owned by a component.</dd></dl></div><footer><small>Updated weekly</small></footer></section>

Key points

  • children is whatever sits between a component's tags, rendered with {children}.
  • Fragments group siblings without adding DOM nodes. Use the Fragment form when a key is needed.
  • Composition (children, slot props) is the React way to reuse UI, instead of inheritance.
  • Named props such as header and footer make multi-slot layouts clear.
  • Prefer explicit props over manipulating children with the Children utilities.

Common mistakes

  • Wrapping siblings in an extra div and breaking table or grid markup.
  • Using the shorthand <> when a key is required inside a map.
  • Reaching for inheritance to share UI between components.
  • Forgetting to render {children}, so the content never appears.

Follow-ups

  • How would you let a parent customise several areas of a child, such as header and footer?
  • When would you use React.Children, and why is it discouraged?
  • Why can passing JSX as children defeat memo?

Tips

  • Explain that composition is the answer to "how do I reuse components". Many answers wander into HOCs.
  • Show the keyed fragment case. It proves hands-on experience.
  • Keep to one example that shows children and slots together.
28.react-0028Easyfresher

What does "lifting state up" mean, and when should you do it?

Lifting state up means moving state from a child to the nearest common parent of the components that need it, then passing the value down as props and the setter (or a callback) down for changes. Do it when two components must stay in sync, such as a search box and a results list. Keep state as low in the tree as possible and lift it only as far as needed.

Full answer

Data in React flows one way, from parent to child. Siblings cannot read each other's state directly. If a search box and a list of results must agree on the same query, neither can own it alone.

The solution is to move the state to their closest common parent. The parent holds query, passes it to the list as a prop, and passes the box a value and an onChange callback. When the user types, the box calls the callback. The parent updates its state, re-renders, and both children receive the new value. There is now exactly one source of truth.

The opposite problem is lifting too high. If state lives at the top of the app, every change re-renders a large part of the tree, and components become cluttered with props they only pass along. Keep state close to where it is used. Lift only when two or more components need it.

A related decision is whether a value is state at all. In the example, the filtered list is computed during render from the full list and the query. It is not stored separately, so it cannot be out of date.

When the chain of props gets long, alternatives exist: composition, context, or a state library. These are tools for the same problem, giving components access to shared data without passing it by hand.

Lifting state also makes components more reusable. A controlled search box that receives value and onChange can be used anywhere, because it does not own the data.

jsx
import { useState } from 'react';

const students = ['Asha', 'Ravi', 'Meera', 'Ashok'];

function SearchBox({ value, onChange }) {
  return <input value={value} onChange={(e) => onChange(e.target.value)} placeholder="Search students" />;
}

function ResultList({ query }) {
  const matches = students.filter((name) => name.toLowerCase().includes(query.toLowerCase()));
  return (
    <ul>
      {matches.map((name) => (
        <li key={name}>{name}</li>
      ))}
    </ul>
  );
}

export default function App() {
  const [query, setQuery] = useState('');
  return (
    <div>
      <SearchBox value={query} onChange={setQuery} />
      <ResultList query={query} />
    </div>
  );
}

The query lives in App. SearchBox reports changes through onChange, and ResultList reads the same query as a prop. The check typed Asha into the box. Rendered result: <div><input placeholder="Search students" value="Asha"><ul><li>Asha</li></ul></div>

Key points

  • Move state to the closest common parent of the components that need it.
  • Pass the value down as props and changes up through callback props.
  • Keep state as local as possible, and lift only when needed.
  • Compute derived data in render instead of storing a second copy.
  • Components that receive value and onChange are reusable and easy to test.

Common mistakes

  • Keeping a copy of the query in both children and trying to sync them with effects.
  • Lifting all state to the root of the app out of habit.
  • Storing the filtered list in state when it can be computed from the query.
  • Passing the setter down under many layers instead of considering composition or context.

Follow-ups

  • What are the downsides of lifting state too high?
  • How would you avoid re-rendering the whole list on every keystroke for a large data set?
  • When would you replace lifted state with context or a store?

Tips

  • Describe the idea in terms of a single source of truth.
  • Say "as low as possible, as high as necessary". It shows judgement.
  • Use a familiar example, such as a search box with a list.
29.react-0029Easyfresher

Why must state be updated immutably in React, and how do you update objects and arrays?

React decides whether to re-render by comparing the old and new state with Object.is. If you mutate an object or array in place and pass the same reference to the setter, React sees no change and may skip the update. Instead create a new object or array: use spread, map, filter and slice instead of push, splice or direct assignment. Immutability also makes memoization and time-travel debugging reliable.

Full answer

Objects and arrays are compared by reference. If you write students.push(x) and then call setStudents(students), the reference is the same, so React treats the state as unchanged and skips the re-render. The data changed but nothing shows it.

The rule is to treat state as read-only and give React a fresh copy for every change. For objects, spread the old one and override a field: setUser({ ...user, name: 'Asha' }). For arrays, use methods that return new arrays. To add, [...list, item]. To remove, list.filter((x) => x.id !== id). To change one item, list.map((x) => x.id === id ? { ...x, done: true } : x). Avoid push, pop, splice, sort and reverse on state itself, since they mutate. Sort a copy: [...list].sort(...), or use toSorted.

Nested objects need a copy at each level you change: { ...state, address: { ...state.address, city: 'Pune' } }. Spread is shallow, so unchanged nested parts stay shared, which is fine and cheap.

Immutability gives practical benefits. memo and dependency arrays rely on changed references to detect change. Previous state stays intact, so undo features are easy. And bugs from one component mutating data another is reading disappear.

When nested updates get heavy, a library such as Immer lets you write mutating-looking code that produces an immutable result. Redux Toolkit uses it internally.

The example adds an item, flips a field and removes another, using only copies.

jsx
import { useState } from 'react';

export default function Students() {
  const [students, setStudents] = useState([
    { id: 1, name: 'Asha', passed: true },
    { id: 2, name: 'Ravi', passed: false },
  ]);

  function add() {
    setStudents((list) => [...list, { id: list.length + 10, name: 'Meera', passed: true }]);
  }

  function toggle(id) {
    setStudents((list) => list.map((s) => (s.id === id ? { ...s, passed: !s.passed } : s)));
  }

  function remove(id) {
    setStudents((list) => list.filter((s) => s.id !== id));
  }

  return (
    <div>
      <button onClick={add}>Add Meera</button>
      <ul>
        {students.map((s) => (
          <li key={s.id}>
            {s.name}: {s.passed ? 'passed' : 'not passed'}
            <button onClick={() => toggle(s.id)}>Toggle {s.name}</button>
            <button onClick={() => remove(s.id)}>Remove {s.name}</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Every update creates a new array and, where needed, a new object for the changed student. The check added Meera, toggled Ravi and removed Asha. Rendered result: <div><button>Add Meera</button><ul><li>Ravi: passed<button>Toggle Ravi</button><button>Remove Ravi</button></li><li>Meera: passed<button>Toggle Meera</button><button>Remove Meera</button></li></ul></div>

Key points

  • React compares state by reference with Object.is, so mutated state with the same reference does not re-render.
  • Use spread, map, filter and slice to build new objects and arrays.
  • Copy every level you change in a nested structure.
  • Sort or reverse a copy, never the state array.
  • Immer can simplify deeply nested updates.

Common mistakes

  • Calling push or splice on the state array and passing the same array to the setter.
  • Using sort or reverse directly on state.
  • Updating a nested field with a shallow spread and losing the rest of the nested object.
  • Believing a deep clone of everything is needed. Copy only the path you change.

Follow-ups

  • How does Immer let you write mutating code safely?
  • Why does React's dependency comparison use Object.is?
  • How would you update an item inside a nested array of objects?

Tips

  • Start with the reference-equality reason. It explains why the rule exists.
  • Know one operator for add, remove and update. Interviewers often ask live.
  • Mention Immer as the practical shortcut for deep updates.
30.react-0030Mediummid

How do you fetch data in useEffect safely, and how do you avoid race conditions?

Start the request inside the effect, store the result in state, and return a cleanup function that cancels the request with an AbortController (or marks it as ignored). Without cleanup, a slow response for an old id can arrive after a fast response for a new id and overwrite it. Handle loading and error states too. For real apps, a data library or framework loader is usually better than hand-written effects.

Full answer

A basic effect fetch looks simple: when userId changes, call the API and set the result. The problem is ordering. Imagine the user goes from id 1 to id 2 quickly. Request 1 is slow, request 2 is fast. Request 2 finishes and shows user 2, then request 1 finishes and replaces it with user 1. The screen now says user 1 while the page title says user 2. This is a race condition.

The fix lives in the effect's cleanup. When userId changes, React runs the previous cleanup before the new effect. If the cleanup aborts the previous request, its result is never applied. With fetch, pass { signal: controller.signal } and call controller.abort() in the cleanup. Ignore the resulting AbortError, because it is expected. A simpler, older version uses a local let ignore = false flag that the cleanup sets to true, and the callback checks before calling setState.

A solid effect also handles the other states: loading while waiting, error when the request fails (check response.ok, since fetch does not reject on a 404), and reset of old data when the id changes. Another clean route is to give the component a key, such as key={userId}, so each id gets fresh state.

In development, StrictMode runs the effect twice, so you will see two requests. The cleanup cancels the first. This is intentional and not a bug in your code.

Effects have limits for data work. They run only on the client, after the first paint, which delays data, and you must write caching, retries and deduplication yourself. Libraries such as TanStack Query and SWR solve these, and frameworks load data in route loaders or Server Components. In React 19, the use API with Suspense is the built-in way to read a promise during render.

The example uses a simulated request so it can run without a network. It rejects with an AbortError when cancelled, as fetch does.

jsx
import { useEffect, useState } from 'react';

function fakeFetchUser(id, signal) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve({ id, name: 'User ' + id }), 100);
    signal.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(new DOMException('Aborted', 'AbortError'));
    });
  });
}

function UserCard({ userId }) {
  const [state, setState] = useState({ status: 'loading', user: null });

  useEffect(() => {
    const controller = new AbortController();
    setState({ status: 'loading', user: null });

    fakeFetchUser(userId, controller.signal)
      .then((user) => setState({ status: 'done', user }))
      .catch((error) => {
        if (error.name === 'AbortError') {
          console.log('request for user ' + userId + ' was cancelled');
        } else {
          setState({ status: 'error', user: null });
        }
      });

    return () => controller.abort();
  }, [userId]);

  if (state.status === 'loading') return <p>Loading user {userId}...</p>;
  if (state.status === 'error') return <p>Could not load user.</p>;
  return <p>{state.user.name}</p>;
}

export default function App() {
  const [userId, setUserId] = useState(1);
  return (
    <div>
      <button onClick={() => setUserId((id) => id + 1)}>Next user</button>
      <UserCard userId={userId} />
    </div>
  );
}

The check pressed Next user twice before any request finished. The first two requests were cancelled and only user 3 was shown. Output of the run: request for user 1 was cancelled request for user 2 was cancelled Final markup: <div><button>Next user</button><p>User 3</p></div>

Key points

  • Out-of-order responses cause race conditions when a dependency changes quickly.
  • Cancel the old request in the effect cleanup with AbortController, or ignore its result with a flag.
  • Handle loading, error and non-OK responses. fetch does not reject on a 404.
  • StrictMode double requests in development are expected, not a bug.
  • Prefer a data library, route loader or Server Components for real applications.

Common mistakes

  • Skipping cleanup, so a slow old response overwrites a newer one.
  • Making the effect callback async directly. Define an inner async function and call it.
  • Treating a 404 or 500 as success because fetch resolved.
  • Forgetting to reset or show loading state when the id changes.
  • Fetching in an effect for data that a framework loader or a server component could provide earlier.

Follow-ups

  • How would the same fetch look with the use API and Suspense?
  • What does a library such as TanStack Query add over a hand-written effect?
  • How do you avoid a request waterfall between parent and child components?

Tips

  • Describe the failure first (slow response 1 beats fast response 2). It proves you understand the race.
  • Show AbortController, then say what you would use in production. Interviewers like candidates who know the limits of effects.
  • Mention the StrictMode double call before they ask.
31.react-0031Mediummid

When does React keep a component's state and when does it reset it? How can you reset state on purpose?

React ties state to a component's position in the tree and its type. If the same component type renders at the same position, state is kept, even when props change. If the type changes, the position disappears, or the key changes, the component unmounts and its state is destroyed. Give a component a key that changes, such as key={userId}, to reset it deliberately. Never define a component inside another one.

Full answer

State is not stored inside the function. React stores it in a tree of fibers, one per component instance, and finds it by position. So the same Profile component at the same spot keeps its state across renders, even if you pass a different user. That surprises people who expect new props to start fresh.

State is kept when the component type and position match the previous render. State is reset when the type at that position changes (a Counter replaced by a Timer), when the component is not rendered for a moment, or when its key changes.

This gives two practical tools. To keep state, render the component in the same place. To reset state, use a key. A form for editing user A that shows user B after navigation should be <EditForm key={user.id} user={user} />. Changing the key tells React "this is a different instance", so it unmounts the old one and mounts a new one. That is cleaner than resetting each field in an effect.

One bug creates state resets by accident: defining a component inside another component. Every render of the outer component creates a new function, so React sees a new type and remounts the inner one, losing state and focus. Define components at module level and pass data through props.

Conditional rendering can also move components. {isAdmin && <Panel />} before a list shifts position in arrays differently than a ternary with null in the same slot. When elements share a position, JSX such as cond ? <A /> : <A /> keeps the same instance because the type and position match. Use keys if you want different instances.

The demo shows an input with no key and one with a key, after switching person.

jsx
import { useState } from 'react';

function Draft({ person, label }) {
  const [text, setText] = useState('');
  return (
    <p>
      <label>
        {label} for {person}: <input value={text} onChange={(e) => setText(e.target.value)} />
      </label>
      <span> draft text: {text}</span>
    </p>
  );
}

export default function App() {
  const [person, setPerson] = useState('Asha');
  return (
    <div>
      <button onClick={() => setPerson('Ravi')}>Switch person</button>
      <Draft person={person} label="Without key" />
      <Draft key={person} person={person} label="With key" />
    </div>
  );
}

The check typed a different draft into each input and then switched the person. The draft without a key stays, although it now belongs to a different person. The draft with key={person} starts empty. Rendered result: <div><button>Switch person</button><p><label>Without key for Ravi: <input value="Asha"></label><span> draft text: Asha</span></p><p><label>With key for Ravi: <input value=""></label><span> draft text: </span></p></div>

Key points

  • State belongs to a component's position in the tree plus its type.
  • Same type at the same position keeps state even if the props change.
  • A different type, a removed component or a different key resets state.
  • Use key={id} to reset a component when its identity changes.
  • Never define components inside other components, since this remounts them every render.

Common mistakes

  • Defining a component inside another component and losing its state on every render.
  • Expecting new props to reset a component's state.
  • Resetting forms by copying props into state and syncing them with effects.
  • Using an index as a key where the item identity changes.

Follow-ups

  • Why does a component defined inside another component lose focus after each keystroke?
  • How does the key trick compare with resetting state inside an effect?
  • What happens to state when a component is hidden with CSS instead of removed?

Tips

  • Say "position and type" in the first sentence. It names the actual rule.
  • Show the key reset as the recommended answer. Many people say "use useEffect".
  • Mention the nested component bug, which is a common review comment.
32.react-0032Mediummid

How do React.lazy and Suspense implement code splitting, and when should you use them?

React.lazy takes a function that calls dynamic import() and returns a component that loads its code the first time it renders. While it loads, the nearest Suspense boundary shows a fallback. The bundler places the imported module in a separate chunk, so users download it only when needed. Use it for routes, modals and heavy widgets such as charts, not for tiny components.

Full answer

A single JavaScript bundle forces every visitor to download code for pages and features they may never open. Code splitting breaks the bundle into chunks that load on demand.

const Chart = lazy(() => import('./Chart.jsx')) does this. The call to import() is a dynamic import: the bundler (Vite, webpack, Rollup) sees it and emits a separate chunk. The lazy component fetches that chunk the first time it is rendered. Until it arrives, React suspends and the nearest <Suspense fallback={...}> above shows the fallback.

Rules to remember. The module must have a default export that is a component. For a named export, adapt it: lazy(() => import('./charts').then((m) => ({ default: m.Chart }))). Call lazy at module level, not inside a component, otherwise a new lazy type is created on every render and its state resets. Wrap lazy components in Suspense, and in an error boundary, because a failed network request for the chunk throws an error.

The best places to split are routes (each page is a chunk), modals and panels that appear after a click, and large libraries used in one corner of the UI. Splitting a ten-line component costs a network request and gives no saving.

For smoother navigation, update state inside startTransition so React keeps the old screen visible instead of replacing it with the fallback. You can also preload a chunk early, for example on hover, by calling the same import() ahead of time.

Frameworks often split by route automatically, and Server Components keep server-only code out of the browser bundle entirely, so manual lazy is mostly for client-side apps and heavy client widgets.

Chart.jsx, in its own file, is a plain component:

jsx
export default function Chart() {
  return <p>Chart loaded: 3 bars</p>;
}
jsx
import { lazy, Suspense, useState } from 'react';

const Chart = lazy(() => import('./Chart.jsx'));

export default function Dashboard() {
  const [showChart, setShowChart] = useState(false);

  return (
    <div>
      <button onClick={() => setShowChart(true)}>Show chart</button>
      {showChart && (
        <Suspense fallback={<p>Loading chart...</p>}>
          <Chart />
        </Suspense>
      )}
    </div>
  );
}

This file expects the Chart.jsx module shown in the answer next to it. The chunk is requested only after the button is pressed. In this check the bundler placed Chart.jsx in the same output file, so the lazy load resolves at once, whereas a production build emits a separate chunk. Rendered result after the click: <div><button>Show chart</button><p>Chart loaded: 3 bars</p></div>

Key points

  • lazy(() => import('./X')) loads a component's code on first render.
  • Suspense shows a fallback while the chunk loads. Add an error boundary for failures.
  • The imported module must have a default export, or be adapted with then.
  • Call lazy at module level, never inside a component.
  • Split routes, modals and heavy widgets, not small components.

Common mistakes

  • Calling lazy inside a component, which recreates the lazy type on each render.
  • Importing a named export without mapping it to default.
  • Forgetting a Suspense boundary, which makes React throw an error.
  • Splitting very small components and adding extra network requests.
  • Not handling chunk load failures after a new deployment.

Follow-ups

  • How would you avoid a loading spinner flash when navigating between lazy routes?
  • How can you preload a lazy component before the user needs it?
  • How do Server Components change the need for manual code splitting?

Tips

  • Mention where you would split (routes, modals, heavy widgets). It shows judgement.
  • State the default-export rule and the named-export workaround.
  • Add the failure case: a chunk can fail to load, so use an error boundary.
33.react-0033Mediummid

How do form actions work in React 19, and what do useActionState and useFormStatus do?

In React 19 you can pass a function to a form's action prop. React runs it as an action when the form is submitted, passes it the FormData, handles the pending state with a transition, and resets uncontrolled fields when it finishes. useActionState wraps an action and gives you its latest result plus a wrapped function to use as action. useFormStatus, used in a child of the form, reads whether that form is pending.

Full answer

Before React 19, a form submit needed an onSubmit handler, preventDefault, a controlled input for each field, and manual loading and error state. Actions reduce that to a function.

<form action={fn}> makes React call fn(formData) on submit. The function can be async. React runs it inside a transition, so the UI stays responsive, and it takes care of pending state. When the action finishes, React resets uncontrolled fields in the form. If you need to keep the typed value after an error, return it from the action and use it as a defaultValue.

useActionState(action, initialState) returns [state, formAction, isPending]. The action you pass receives (previousState, formData) and returns the next state, such as an error message or a success flag. Pass formAction to the form. The state updates with whatever the action returns. This is how a form shows validation errors without extra useState calls.

useFormStatus() from react-dom returns { pending, data, method, action } for the parent form. It must be called from a component rendered inside the form, not from the component that renders the form tag. That makes it ideal for a reusable submit button that disables itself while saving.

Actions are not limited to client code. With a framework that supports Server Functions, the action can be a function marked "use server", and the same form works before JavaScript loads (progressive enhancement). Because those are public endpoints, validate input and check permissions on the server.

For instant feedback, combine actions with useOptimistic. For richer control or complex fields, controlled inputs and libraries such as React Hook Form remain fine. Actions are an addition, not a replacement for every form.

jsx
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';

async function saveName(previousState, formData) {
  const name = String(formData.get('name') ?? '').trim();
  await new Promise((resolve) => setTimeout(resolve, 20));
  if (name.length < 3) {
    return { ok: false, message: 'Name needs at least 3 letters' };
  }
  return { ok: true, message: 'Saved ' + name };
}

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Saving...' : 'Save'}
    </button>
  );
}

export default function ProfileForm() {
  const [state, formAction] = useActionState(saveName, { ok: null, message: '' });

  return (
    <form action={formAction}>
      <input name="name" />
      <SubmitButton />
      <p>{state.message}</p>
    </form>
  );
}

The action validates the name and returns a message. SubmitButton reads the pending flag from the form around it. The check submitted Al first and then Asha. In both cases React emptied the input after the action finished, so a real form returns the typed value in its state to keep it. Output of the run: after "Al": Name needs at least 3 letters | input value is "" after "Asha": Saved Asha | input value is ""

Key points

  • A form accepts a function in action. React passes FormData, runs it in a transition and manages pending state.
  • useActionState(action, initial) returns the state, a form action and a pending flag. The action receives the previous state first.
  • useFormStatus reads the parent form's pending state and must be called from a child component.
  • React resets uncontrolled fields when the action finishes, even if it returned an error.
  • Server Functions use the same form API and need server-side validation.

Common mistakes

  • Calling useFormStatus in the same component that renders the form element, where it always reports not pending.
  • Writing the action as (formData) when it is wrapped by useActionState, which passes previousState first.
  • Expecting typed values to remain after the action. Uncontrolled fields are reset.
  • Treating a Server Function as private. It is reachable by anyone who can send a request.

Follow-ups

  • How would you keep the user's input after a validation error?
  • How does useOptimistic combine with a form action?
  • What does "progressive enhancement" mean for a form that uses a Server Function?

Tips

  • Show the order of arguments, previous state first. It is a common slip.
  • Explain why useFormStatus must be in a child. It is a frequent follow-up.
  • Be balanced: say when you would still choose a controlled form or a form library.
34.react-0034Mediummid

What do useTransition and useDeferredValue do, and when would you use each?

Both mark some updates as lower priority so urgent ones, like typing, stay responsive. useTransition gives you startTransition to wrap a state update and an isPending flag, which is useful when you control the setter. useDeferredValue takes a value and returns a lagging copy, which is useful when the value comes from props or a parent you do not control. Neither makes slow work faster. They stop it from blocking input.

Full answer

Not every state update deserves the same urgency. Typing in a search box must feel instant, while re-rendering a long result list below it can wait a moment. React 18 introduced transitions to express this.

const [isPending, startTransition] = useTransition() returns a function. Updates inside startTransition(() => setTab('reports')) are marked as a transition. React renders them in the background and can interrupt that render if a more urgent update (such as a keystroke) arrives. While waiting, isPending is true, so you can dim the old content. In React 19, a transition can also contain async functions, which is how actions are tracked.

useDeferredValue(value) returns a copy of the value that may lag behind. React first renders with the old copy, so the urgent part (the input) updates at once, then re-renders with the new copy in the background. Use it when the slow component receives the value as a prop and you cannot wrap the setter. It is like debouncing without a fixed delay, and it adapts to the speed of the device.

How do you choose? If you own the state update, use useTransition. If the value arrives from somewhere else, or you want a lagging value for one subtree, use useDeferredValue. Both rely on the slow work being a normal React render. They do not help with a slow network call or a long script outside React. To make renders cheaper in the first place, memoize the slow list or reduce its size.

Transitions have rules: the setter called inside must be the React state setter, text input updates should not be wrapped in a transition (input state must stay urgent), and a transition that suspends keeps the old UI instead of the fallback.

The example filters 2000 names with a deferred query and switches a tab through a transition.

jsx
import { memo, useDeferredValue, useState, useTransition } from 'react';

const names = Array.from({ length: 2000 }, (_, i) => 'Student ' + i);

const ResultList = memo(function ResultList({ query }) {
  const matches = names.filter((name) => name.includes(query));
  return <p>{matches.length} matches</p>;
});

export default function SearchPage() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);
  const [tab, setTab] = useState('students');
  const [isPending, startTransition] = useTransition();

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />
      <ResultList query={deferredQuery} />
      <button onClick={() => startTransition(() => setTab('reports'))}>Open reports</button>
      <p>
        Tab: {tab} {isPending ? '(loading)' : ''}
      </p>
    </div>
  );
}

The input updates immediately while ResultList renders with the deferred query. The check typed Asha, which matches none of the names. The tab update runs inside a transition. Rendered result: <div><input placeholder="Search" value="Asha"><p>0 matches</p><button>Open reports</button><p>Tab: reports </p></div>

Key points

  • Both mark updates as non-urgent so urgent input updates stay responsive.
  • useTransition wraps an update you control and gives isPending.
  • useDeferredValue defers a value you receive and returns a lagging copy.
  • They do not speed up slow code. They only prevent blocking.
  • Do not put controlled input updates inside a transition.

Common mistakes

  • Wrapping a controlled input's setter in startTransition, which makes typing lag.
  • Expecting useDeferredValue to speed up a slow render. It only prioritizes.
  • Using transitions for work that is slow outside React, such as a long synchronous script.
  • Forgetting memo on the slow child, so it re-renders with the urgent value anyway.

Follow-ups

  • How does a transition interact with Suspense?
  • Why is useDeferredValue called an adaptive debounce?
  • How would you show a pending indicator while the deferred value is behind?

Tips

  • Start from the user experience (typing must stay instant), then name the hooks.
  • Know the choice rule: setter you own versus value you receive.
  • Say that memoizing the slow child is part of making useDeferredValue work.
35.react-0035Mediummid

How does client-side routing work with React Router? Explain routes, nested layouts, params and loaders.

React Router matches the browser URL against a list of routes and renders the matching components without a full page reload. Nested routes render children through Outlet inside a layout. Dynamic segments like :id are read with useParams, and in data mode a route's loader fetches data before rendering, available through useLoaderData. Link and NavLink change the URL without a request to the server.

Full answer

In a single-page app the server returns one HTML page, and JavaScript decides what to show for each URL. A router listens for URL changes, finds the matching route and renders its component. Links update the address with the History API, so there is no page reload.

A route has a path and a component. Paths can contain dynamic segments: students/:id matches /students/2, and useParams() returns { id: '2' }. A splat path * catches unknown URLs and is the usual place for a Not Found page.

Nested routes mirror nested UI. A parent route renders a layout, such as a navigation bar, and an <Outlet /> marks where the matching child appears. An index route is the default child for the parent's own path.

React Router has three modes: declarative (BrowserRouter with Routes and Route elements), data (createBrowserRouter with route objects, loaders, actions and RouterProvider), and framework (a Vite plugin that adds file-based features and server rendering). Data mode, used in the example, lets a route declare a loader. The router calls it before rendering, so the component gets data with useLoaderData() and avoids the render-then-fetch waterfall. Actions handle form submissions and then revalidate the loaders.

Navigation uses Link for a plain link and NavLink, which adds an active class for styling the current page. For code-driven navigation, use useNavigate, and for redirects in loaders, return redirect('/login'). Alternatives are TanStack Router, which has type-safe routes, and the file routing of Next.js. Choose by the framework you are already using.

Remember the server too. For a deployed SPA, every URL must serve index.html, otherwise a refresh on /students returns a 404 from the host.

jsx
import {
  createBrowserRouter,
  Link,
  NavLink,
  Outlet,
  RouterProvider,
  useLoaderData,
  useParams,
} from 'react-router';

const students = [
  { id: '1', name: 'Asha' },
  { id: '2', name: 'Ravi' },
];

function Layout() {
  return (
    <div>
      <nav>
        <NavLink to="/">Home</NavLink> <NavLink to="/students">Students</NavLink>
      </nav>
      <Outlet />
    </div>
  );
}

function Home() {
  return <h1>Home</h1>;
}

function StudentList() {
  const list = useLoaderData();
  return (
    <ul>
      {list.map((s) => (
        <li key={s.id}>
          <Link to={'/students/' + s.id}>{s.name}</Link>
        </li>
      ))}
    </ul>
  );
}

function StudentDetail() {
  const { id } = useParams();
  const student = useLoaderData();
  return (
    <h2>
      Student {id}: {student.name}
    </h2>
  );
}

function NotFound() {
  return <h2>Page not found</h2>;
}

const router = createBrowserRouter([
  {
    path: '/',
    Component: Layout,
    children: [
      { index: true, Component: Home },
      { path: 'students', loader: () => students, Component: StudentList },
      {
        path: 'students/:id',
        loader: ({ params }) => students.find((s) => s.id === params.id),
        Component: StudentDetail,
      },
      { path: '*', Component: NotFound },
    ],
  },
]);

export default function App() {
  return <RouterProvider router={router} />;
}

The Layout stays on screen while the Outlet swaps the page. The loaders return their data before the page components render. The check clicked Students and then the Ravi link. Run output, one snapshot per page: home page: Home StudentsHome students page: Home StudentsAshaRavi detail page: Home StudentsStudent 2: Ravi

Key points

  • A router maps URLs to components and updates the address without reloading the page.
  • Nested routes use Outlet. Dynamic segments such as :id are read with useParams.
  • Data mode adds loaders and actions, which fetch before render and avoid waterfalls.
  • Link and NavLink navigate without a server request. useNavigate is for code-driven moves.
  • A static host must send index.html for all paths so refresh works.

Common mistakes

  • Using a plain anchor tag, which reloads the page, instead of Link.
  • Forgetting an index route or a catch-all route.
  • Forgetting that the host must serve index.html for deep links.
  • Fetching in a component effect when a loader would remove the waterfall.
  • Mixing up the modes and importing APIs that exist only in framework mode.

Follow-ups

  • How do loaders and actions avoid fetch waterfalls?
  • How would you protect a route that needs a logged-in user?
  • How does route-level code splitting work with a router?

Tips

  • Name the three router modes. It shows current knowledge of the library.
  • Explain Outlet with a layout example.
  • Mention the server fallback to index.html. It is a classic deployment bug.
36.react-0036Mediummid

How do you test React components? What does React Testing Library encourage, and how do you test user interactions?

Use a test runner such as Vitest or Jest with React Testing Library. Render the component, find elements the way a user would (by role, label or text), simulate actions with user-event and assert on what the user sees. Test behaviour, not implementation details such as internal state or component names. Mock only the boundaries, such as network calls and callback props.

Full answer

A good component test answers one question: does the component behave correctly for the user? So tests avoid reaching into state or calling hooks directly. Instead they render the component into a simulated DOM (jsdom), interact with it, and check the screen.

React Testing Library (RTL) provides render and the screen object with queries. The preferred query order follows accessibility: getByRole with a name, getByLabelText for form fields, getByText for content, and getByTestId only as a last resort. Using roles has a second benefit: tests fail when the markup is not accessible.

For interaction, use @testing-library/user-event. userEvent.setup() returns a user with methods like click and type that fire the same events a browser does, including focus and key presses. They are async, so await them. For elements that appear later, use findBy queries, which wait, or waitFor. Use queryBy when you expect an element not to exist.

Assertions come from the runner and from jest-dom matchers such as toBeInTheDocument and toBeDisabled. A callback prop is checked with a mock function: const onSubmit = vi.fn(), then expect(onSubmit).toHaveBeenCalledWith(...). Network calls are best handled with a mock at the network layer, such as Mock Service Worker, so the component's own fetch code is exercised.

Custom hooks can be tested with renderHook. Pure logic, such as reducers, needs no React at all.

Keep a balance. Most tests are small component and hook tests, a few cover a page with several components, and a handful of end-to-end tests with Playwright or Cypress cover critical flows in a real browser. Snapshot tests of large trees tend to break for no reason and are best used sparingly.

jsx
import { useState } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom/vitest';

function Counter({ initial = 0 }) {
  const [count, setCount] = useState(initial);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Add one</button>
    </div>
  );
}

function EmailForm({ onSubmit }) {
  const [email, setEmail] = useState('');
  const invalid = email.length > 0 && !email.includes('@');

  function handleSubmit(event) {
    event.preventDefault();
    onSubmit({ email });
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email
        <input value={email} onChange={(e) => setEmail(e.target.value)} />
      </label>
      {invalid && <p role="alert">Enter a valid email</p>}
      <button type="submit" disabled={invalid || email === ''}>
        Send
      </button>
    </form>
  );
}

afterEach(cleanup);

describe('Counter', () => {
  it('starts at the given value', () => {
    render(<Counter initial={5} />);
    expect(screen.getByText('Count: 5')).toBeInTheDocument();
  });

  it('adds one when the button is clicked', async () => {
    const user = userEvent.setup();
    render(<Counter />);
    await user.click(screen.getByRole('button', { name: 'Add one' }));
    expect(screen.getByText('Count: 1')).toBeInTheDocument();
  });
});

describe('EmailForm', () => {
  it('shows an error and disables Send for a bad email', async () => {
    const user = userEvent.setup();
    render(<EmailForm onSubmit={vi.fn()} />);
    await user.type(screen.getByLabelText('Email'), 'asha');
    expect(screen.getByRole('alert')).toHaveTextContent('Enter a valid email');
    expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();
  });

  it('calls onSubmit with the typed email', async () => {
    const user = userEvent.setup();
    const onSubmit = vi.fn();
    render(<EmailForm onSubmit={onSubmit} />);
    await user.type(screen.getByLabelText('Email'), 'asha@example.com');
    await user.click(screen.getByRole('button', { name: 'Send' }));
    expect(onSubmit).toHaveBeenCalledWith({ email: 'asha@example.com' });
  });
});

In a real project the components live in their own files and the tests sit next to them. They are in one file here only so the example is complete. The file ran under Vitest with the jsdom environment, and these tests passed on two consecutive runs: Counter > starts at the given value Counter > adds one when the button is clicked EmailForm > shows an error and disables Send for a bad email EmailForm > calls onSubmit with the typed email

Key points

  • Test what the user sees and does, not internal state.
  • Query by role, label or text. Use test ids only when nothing else works.
  • user-event simulates real interactions and is async, so await it.
  • Use findBy for async appearance and queryBy to assert absence.
  • Mock at the boundary (callbacks, network) and keep a few end-to-end tests for key flows.

Common mistakes

  • Testing implementation details such as state values or internal function names.
  • Querying by test id when a role or label query is available.
  • Forgetting to await user-event calls or findBy queries.
  • Using getBy to assert that something is absent. Use queryBy.
  • Large snapshot tests that fail on harmless markup changes.

Follow-ups

  • How would you test a component that fetches data on mount?
  • How do you test a custom hook, and when is renderHook the wrong tool?
  • Which flows would you cover with end-to-end tests instead of component tests?

Tips

  • Say "test what the user sees". It is the core idea of Testing Library.
  • Know the query priority order and why role queries help accessibility.
  • Mention the testing mix: many small tests, a few page tests, a few end-to-end tests.
37.react-0037Mediummid

What is a stale closure in React, how does it happen in effects, and how does useEffectEvent help?

Every render creates new functions that capture that render's props and state. An effect or callback that runs later may still hold the values from an older render, which are stale. You can fix it by adding the value to the dependency array, by using an updater function, or, when the effect should not re-run for a value it only reads, by moving that reading into a function made with useEffectEvent, which always sees the latest props and state.

Full answer

A closure is a function that remembers the variables around it when it was created. In React each render is a separate call of your component, so every function created in it remembers that render's values. Usually this is exactly what you want. It becomes a bug when an old function lives longer than its render: an interval, a timer, a subscription, or an event listener registered once.

Consider an effect with [] dependencies that starts an interval and reads count inside. The effect ran during the first render, so it saw count as 0. Every tick still sees 0, even after the state has moved on. This is a stale closure.

There are three standard fixes. The first is to list the value in the dependency array so the effect restarts with fresh values. That is right when the effect truly depends on the value, but it reconnects a chat or restarts a timer each time. The second is to avoid reading state: use an updater function, setCount((c) => c + 1), which does not need the current value. The third applies to code that should react to one value but only read another. For this, React 19.2 provides useEffectEvent.

const onConnected = useEffectEvent(() => { ... }) creates a function that always sees the latest props and state, yet is not a reactive value, so it is left out of the dependency array. In the example, the connection depends on roomId, but the message should use the current theme. Without useEffectEvent, you must either put theme in the dependencies (reconnecting whenever the theme changes) or read a stale theme.

Rules: call an Effect Event only from inside effects, not during render and not from child components, and do not use it to hide a dependency that should trigger the effect. The lint rule reminds you.

This is the stale version, shown on purpose. It connects once, but reports the first theme forever, and the linter warns about the missing dependency:

jsx
import { useEffect } from 'react';

function ChatRoom({ roomId, theme }) {
  useEffect(() => {
    const timer = setTimeout(() => console.log('Connected to ' + roomId + ' with ' + theme), 30);
    return () => clearTimeout(timer);
  }, [roomId]); // theme is read but not listed
  return <h2>{roomId}</h2>;
}
jsx
import { useEffect, useEffectEvent, useState } from 'react';

function createConnection(roomId, onConnected) {
  const timer = setTimeout(onConnected, 200);
  return { disconnect: () => clearTimeout(timer), roomId };
}

function ChatRoom({ roomId, theme }) {
  const onConnected = useEffectEvent(() => {
    console.log('Connected to ' + roomId + ' with the ' + theme + ' theme');
  });

  useEffect(() => {
    const connection = createConnection(roomId, onConnected);
    return () => connection.disconnect();
  }, [roomId]);

  return <h2>Room: {roomId}</h2>;
}

export default function App() {
  const [theme, setTheme] = useState('light');
  return (
    <div>
      <button onClick={() => setTheme('dark')}>Switch theme</button>
      <ChatRoom roomId="general" theme={theme} />
    </div>
  );
}

The connection depends only on roomId. The check switched the theme to dark before the connection finished, and the message used the latest theme without reconnecting. Output of the run: Connected to general with the dark theme

Key points

  • Each render creates functions that capture that render's values.
  • Long-lived callbacks (timers, listeners, subscriptions) can hold stale values.
  • Fix by adding dependencies, using updater functions, or using useEffectEvent for read-only logic.
  • useEffectEvent (React 19.2) always sees the latest values and is not a dependency.
  • Call Effect Events only inside effects. Never use them to silence the dependency lint.

Common mistakes

  • Using an empty dependency array while reading state inside an interval, and getting a frozen value.
  • Disabling the exhaustive-deps lint rule to hide the problem.
  • Calling an Effect Event during render or passing it to a child component.
  • Moving a value that should restart the effect into an Effect Event.

Follow-ups

  • How would you write a working interval counter without useEffectEvent?
  • What is the difference between a ref that holds the latest value and an Effect Event?
  • Why is it wrong to put an Effect Event in the dependency array?

Tips

  • Start with a one-line definition of closure, then link it to renders. This avoids a vague answer.
  • Offer the three fixes in order of simplicity. It shows range.
  • Note that useEffectEvent is recent. Say which version added it.
38.react-0038Hardsenior

What is concurrent rendering in React 18 and later, and what does it change for the way you write components?

Concurrent rendering means React can start rendering an update, pause it, handle a more urgent update, and then resume or discard the unfinished work. Rendering becomes interruptible, but the commit to the DOM is still one synchronous step. It is enabled by createRoot, and you use it through transitions, useDeferredValue and Suspense. It requires components to be pure, because React may call them more than once or throw the result away.

Full answer

Before React 18, once a render started it ran to the end on the main thread. A slow render of a large list could freeze typing, because the browser could not process input until React finished.

With concurrent rendering the render phase can be interrupted. React splits work into small units on its fiber tree and checks between units whether something more urgent arrived. Updates carry a priority (called a lane internally). A click or keystroke is urgent. An update inside startTransition is not. React renders the urgent one first and commits it. It continues the transition afterwards, restarts it if its inputs changed, or abandons it.

Concurrency is not parallelism or multiple threads. There is still one JavaScript thread. It is also not a feature you switch on by itself: using createRoot makes the concurrent renderer available, and behaviour changes only when you use the features that need it.

Those features are transitions (useTransition, startTransition), deferred values (useDeferredValue), Suspense with data and code loading, and streaming server rendering with selective hydration. In React 19 the Activity component builds on the same machinery to pre-render hidden UI at low priority.

The commit phase stays synchronous. DOM updates and layout effects cannot be interrupted, so users never see half of an update.

The cost is a discipline. Render must be pure. A render may run, be thrown away and run again, so it should not write to variables outside the component, mutate props, or perform side effects. StrictMode helps by rendering twice in development. External stores that change during a render can cause "tearing", where parts of the UI show different values. useSyncExternalStore prevents it.

The example logs the two renders caused by one click: the urgent value first, with the transition value still old, and then the transition value.

jsx
import { useState, useTransition } from 'react';

export default function Demo() {
  const [urgent, setUrgent] = useState(0);
  const [heavy, setHeavy] = useState(0);
  const [isPending, startTransition] = useTransition();

  console.log('render urgent=' + urgent + ' heavy=' + heavy + ' pending=' + isPending);

  function handleClick() {
    setUrgent((n) => n + 1);
    startTransition(() => {
      setHeavy((n) => n + 1);
    });
  }

  return (
    <div>
      <button onClick={handleClick}>Update both</button>
      <p>
        urgent: {urgent}, heavy: {heavy}
      </p>
    </div>
  );
}

One click sets an urgent state and a transition state. React renders the urgent update first, with the transition value still old and isPending true, and then renders the transition. Console output (the first line is the mount): render urgent=0 heavy=0 pending=false render urgent=1 heavy=0 pending=true render urgent=1 heavy=1 pending=false

Key points

  • Concurrent rendering makes the render phase interruptible and prioritized. The commit phase stays synchronous.
  • It is available with createRoot and used through transitions, deferred values and Suspense.
  • It is about scheduling on one thread, not parallelism.
  • Components must be pure, because renders can be repeated or discarded.
  • External stores should use useSyncExternalStore to avoid tearing.

Common mistakes

  • Believing React 18 renders in parallel on several threads.
  • Impure renders, such as writing to a module variable, that break when React repeats a render.
  • Expecting concurrency to be active without using any concurrent feature.
  • Reading from a mutable external store in render instead of using useSyncExternalStore.
  • Assuming the DOM can show a half-finished update. The commit is atomic.

Follow-ups

  • What is tearing, and how does useSyncExternalStore prevent it?
  • How does Suspense behave inside a transition compared with an urgent update?
  • What does Activity do with hidden content in terms of priority?

Tips

  • Separate render (interruptible) from commit (synchronous). It is the most precise way to explain it.
  • Say "one thread, scheduled work". Interviewers listen for the parallelism misconception.
  • Tie it to code discipline: purity is the price of the feature.
39.react-0039Hardsenior

Why does StrictMode render components and run effects twice in development, and what does it tell you about render purity?

In development, StrictMode calls component bodies, state initializers and reducers twice to expose impure code, and it mounts, unmounts and remounts each component once to expose effects without proper cleanup. Production behaviour is unaffected. If double invocation changes the output or leaks something, the code was impure or the cleanup was missing, and the fix is in your code, not by removing StrictMode.

Full answer

React work splits into a render phase, where your component functions run and React works out the next UI, and a commit phase, where DOM changes are applied and effects run. React reserves the right to run the render phase more than once, to pause it, or to throw it away (for example in a transition that is interrupted). For this to be safe, rendering must be a pure calculation: the same props, state and context must always produce the same JSX, and nothing outside the component may be changed.

StrictMode enforces this in development by double invoking: the function body of components, the functions passed to useState, useMemo and useReducer, and reducers. It uses the second result for output and discards the first. If the two calls disagree, the bug shows up at once.

A typical impurity is a module-level counter or array that the component increments or pushes to during rendering. With a double render the value jumps by two. Another is mutating a prop. The fix is to compute from inputs: derive the number from props, or move the change into an event handler or an effect.

StrictMode also stress-tests effects. After the first mount React runs the effect's cleanup and then the effect again, simulating a component that is hidden and shown again, which is exactly what Activity and fast refresh do. A subscription that never unsubscribes now shows two live subscriptions. Ref callbacks get the same check in React 19.

Do not "fix" the symptom by removing StrictMode or adding a flag to skip the second effect run. That only hides the leak that real users hit when navigating back and forth. Make the cleanup complete so setup, cleanup and setup behave like one setup.

In the example, StrictMode wraps the root as in a normal app. Guest numbers are produced by an impure counter, and Seat numbers come from props. React also silences console output during the repeated calls, which is why the example records effect calls in an array.

jsx
import { StrictMode, useEffect } from 'react';
import { createRoot } from 'react-dom/client';

let guestCounter = 0;

function Guest() {
  guestCounter += 1; // impure: writes outside the component while rendering
  return <li>Guest #{guestCounter}</li>;
}

function Seat({ number }) {
  return <li>Seat #{number}</li>; // pure: only reads props
}

const events = [];

function Listener() {
  useEffect(() => {
    events.push('setup');
    return () => {
      events.push('cleanup');
    };
  }, []);

  return <p>Listening</p>;
}

function App() {
  return (
    <>
      <ul>
        <Guest />
        <Guest />
        <Seat number={1} />
        <Seat number={2} />
      </ul>
      <Listener />
    </>
  );
}

const container = document.getElementById('root');
createRoot(container).render(
  <StrictMode>
    <App />
  </StrictMode>
);

setTimeout(() => {
  console.log('markup: ' + container.innerHTML);
  console.log('effect calls: ' + events.join(', '));
}, 50);

StrictMode wraps the root, as in a normal app. Two Guest components should be numbered 1 and 2, but the impure counter is incremented twice per render, so the numbers skip. The Seat numbers stay correct, and the effect runs setup, cleanup, setup. The calls are recorded in an array because React silences console output during the repeated calls. Output of the run: markup: <ul><li>Guest #2</li><li>Guest #4</li><li>Seat #1</li><li>Seat #2</li></ul><p>Listening</p> effect calls: setup, cleanup, setup

Key points

  • The render phase must be pure: same inputs, same output, no outside writes.
  • StrictMode double invokes bodies, initializers and reducers, and double mounts effects in development only.
  • Module-level counters and mutated props are typical impurities. Derive values from props instead.
  • Effects need complete cleanup so setup-cleanup-setup equals one setup.
  • Do not remove StrictMode to silence a symptom.

Common mistakes

  • Counting renders or pushing to arrays in the component body.
  • Removing StrictMode because "effects run twice".
  • Adding a ref flag to skip the second effect run and hiding a missing cleanup.
  • Assuming the double render is a production behaviour.

Follow-ups

  • Which hooks and functions does StrictMode call twice?
  • How does Activity relate to the effect remount check?
  • Why is a module-level cache written during render a purity problem, and how would you write a safe cache?

Tips

  • Frame it as "React may repeat a render", then explain StrictMode as a test for that. This shows understanding of the model.
  • Give the module counter bug as a concrete example.
  • Say that cleanup must be a mirror of setup.
40.react-0040Hardsenior

What is useOptimistic, how does it work with Actions, and what happens if the request fails?

useOptimistic lets you show the expected result of an async action immediately, while the real request is still running. It returns an optimistic copy of some state and a function to apply an update to it. The optimistic value exists only during the action. When the action finishes, React discards it and shows the real state, so a failed request automatically rolls the UI back.

Full answer

Waiting for a server before showing a sent message or a liked post makes interfaces feel slow. An optimistic update shows the likely result at once and reconciles later.

const [optimisticState, addOptimistic] = useOptimistic(state, updateFn) takes the real state and an optional reducer-like function, (currentState, optimisticValue) => newState. It returns the state to render and a setter to call. The setter must be called inside an Action, that is inside a form action or inside startTransition.

The flow is: the user submits, you call addOptimistic(value) straight away, and the UI renders the optimistic state. Then you await the request and update the real state when it succeeds. When the action completes, React stops using the optimistic value and renders whatever the real state now is. On success the real state already includes the item, so it appears to stay. On failure, the real state never changed, so the optimistic item disappears. This automatic rollback is the main benefit. Show an error message in the failure branch so the user knows why the item vanished.

Design notes. Mark optimistic items visually, for example "sending...", so the UI is honest. Use a temporary key or id and replace it with the server id on success. Do not use it for actions where being wrong is costly, such as payments, because showing success that later reverses is harmful. Use it for likes, comments, reordering and toggles.

The hook works together with the other React 19 form features: the form action calls addOptimistic, awaits the request, then updates the real list. Libraries such as TanStack Query have similar optimistic update helpers for data they manage.

In the example the server takes 150 milliseconds, but the message appears at once, flagged as sending.

jsx
import { useOptimistic, useState } from 'react';

function sendToServer(text) {
  return new Promise((resolve) => setTimeout(() => resolve({ id: Date.now(), text }), 150));
}

export default function Chat() {
  const [messages, setMessages] = useState([]);
  const [optimisticMessages, addOptimistic] = useOptimistic(messages, (current, text) => [
    ...current,
    { id: 'pending-' + text, text, sending: true },
  ]);

  async function send(formData) {
    const text = String(formData.get('text'));
    addOptimistic(text);
    const saved = await sendToServer(text);
    setMessages((current) => [...current, saved]);
  }

  return (
    <form action={send}>
      <input name="text" />
      <button type="submit">Send</button>
      <ul>
        {optimisticMessages.map((m) => (
          <li key={m.id}>
            {m.text}
            {m.sending ? ' (sending...)' : ''}
          </li>
        ))}
      </ul>
    </form>
  );
}

The check typed Hello and submitted the form. While the 150 millisecond request is running the list already shows the message with a sending label. After the answer, it appears as a normal message. Output of the run: while sending: Hello (sending...) after server answers: Hello

Key points

  • useOptimistic shows an expected state during an async action and reverts to real state afterwards.
  • Call the setter inside an Action (a form action or startTransition).
  • On failure the optimistic value disappears because real state never changed.
  • Mark optimistic items visibly and replace temporary ids when the server answers.
  • Avoid it for high-risk operations such as payments.

Common mistakes

  • Calling the optimistic setter outside an action or transition.
  • Forgetting to update real state, so the optimistic item vanishes when the action ends.
  • Using optimistic UI for irreversible or high-stakes operations.
  • Not showing an error, so users do not know why the item disappeared after a failure.
  • Reusing the temporary id as the final id.

Follow-ups

  • How would you add error handling and a retry message?
  • How does useOptimistic differ from setting state before the request and reverting in a catch block?
  • How would you handle two optimistic updates in flight at once?

Tips

  • Explain the rollback mechanism. It is the thing interviewers want to hear.
  • Mention honest UI (a pending marker) and the cases where you would not use it.
  • Link it to Actions and forms, since that is where it fits.