Questions 61–80 of 150 · 0 of 20 on this page marked learned
61.react-0061Easyfresher
How does React Native relate to React for the web, and what code can be shared between them?
Both use the same React core: components, props, state, hooks and context. They differ in the renderer and the building blocks. React for the web renders div, span and CSS to the DOM. React Native renders View, Text and Pressable to native iOS and Android views, and styles use JavaScript objects with a Flexbox subset instead of CSS. Hooks, state logic and many utilities can be shared, while the UI components cannot.
Full answer
React is a library for describing UI as a function of state. A renderer turns that description into output. react-dom renders to the browser DOM. React Native provides a renderer that creates native views on the device. Your component model is identical: function components, props, useState, useEffect, context.
What changes are the primitives. There is no div, span, button or img. You use View for containers, Text for all text (text must be inside Text), Image, Pressable or Touchable components for taps, and ScrollView or FlatList for scrolling lists. There is no CSS file. Styles are objects passed to style, created with StyleSheet.create, laid out with Flexbox where column is the default direction. There is no DOM, so no document, window or localStorage. You use platform APIs and libraries such as AsyncStorage instead.
Navigation also differs. Instead of URLs and the browser history, apps use React Navigation or Expo Router with a stack of screens.
Sharing code: business logic, custom hooks, state stores, API clients, validation and types can live in a shared package. UI components are written per platform, or you use a library such as React Native for Web or a universal framework like Expo, which renders React Native primitives on the web.
Modern React Native uses the New Architecture (the JSI and Fabric renderer), which lets React features such as concurrent rendering and Suspense work on mobile. Most teams start with Expo for tooling.
The example runs React Native primitives in a web environment through React Native for Web, with a shared hook.
useCounter is plain React and could be shared with a web app unchanged. The screen uses React Native components. This check ran it on the web through react-native-web (an alias for react-native), which shows the code works but is not a test on a device or the native renderer. Rendered result: <div class="css-view-g5y9jx r-padding-nsbfu8"><div dir="auto" class="css-text-146c3p1 r-fontSize-adyw6z">Taps: 0</div><button role="button" tabindex="0" class="css-view-g5y9jx r-cursor-1loqt21 r-touchAction-1otgn73" type="button"><div dir="auto" class="css-text-146c3p1">Tap me</div></button></div>
Key points
Same React core, different renderer and primitives.
Use View, Text and Pressable instead of div, span and button. All text sits inside Text.
Styles are JavaScript objects with Flexbox, not CSS files.
Share hooks, logic and API code. Write or adapt the UI per platform.
Expo and the New Architecture are the common modern setup.
Common mistakes
Using div, span or CSS class names in React Native.
Putting bare text outside a Text component.
Using window, document or localStorage in code meant for both platforms.
Expecting CSS features such as cascading or pseudo-classes in StyleSheet.
Sharing UI components between web and native without a plan.
Follow-ups
How does FlatList differ from rendering a mapped array in a ScrollView?
What does Expo add to a React Native project?
What is the New Architecture and what does it change for developers?
Tips
Open with "same React, different renderer". It frames the answer correctly.
Name the primitives and say what is shareable.
Mention Expo, since most new projects start there.
62.react-0062Mediummid
How do you add internationalization (i18n) to a React app? Cover translations, plurals and number and date formatting.
Keep user-facing strings in per-language message files and look them up by key through a provider and hook, or use a library such as react-i18next or FormatJS (react-intl). Use the built-in Intl APIs for numbers, dates, currency and plural rules instead of hand-written formatting. Do not concatenate sentence pieces. Store the chosen locale, set the document lang attribute, and plan for text expansion and right-to-left layouts.
Full answer
Internationalization has three parts: translating text, formatting values for a locale, and adapting layout.
For text, replace hard-coded strings with message keys. A provider holds the current locale and messages, and a t('greeting', { name }) function returns the translated string with placeholders filled. Libraries add loading of locale files, fallbacks, and ICU message syntax, which can express plurals and gender in one message. react-i18next and react-intl are the common choices, and frameworks such as Next.js have their own routing support for locales.
Plurals differ by language. English has one and other, but Arabic and Polish have several forms. Do not write count === 1 ? 'item' : 'items'. Use Intl.PluralRules or the library's plural syntax, so each locale picks the right form.
Formatting values uses the Intl objects, which are built into browsers: Intl.NumberFormat for numbers and currency, Intl.DateTimeFormat for dates and times, and Intl.RelativeTimeFormat for "2 days ago". The same number prints as 1,234.5 in English (US) and 1.234,5 in German.
Other rules: never build sentences from pieces, because word order differs by language. Keep the whole sentence as one message with placeholders. Set <html lang> and dir for accessibility and right-to-left languages such as Arabic and Hebrew, and prefer logical CSS properties (margin-inline-start) over left and right. Allow for text that is 30 percent longer. Load only the active locale to keep bundles small.
The example uses a small provider with Intl for plurals, numbers and dates, no library.
The result before the click is English with a US dollar price. After the click the locale is hi, so the greeting, the currency and the date format change. Rendered result: before <div lang="en"><p>Hello, Asha</p><p>1 course</p><p>3 courses</p><p>$1,234.50 on December 4, 2026</p><button>Switch to Hindi</button></div> after <div lang="hi"><p>Namaste, Asha</p><p>1 paathyakram</p><p>3 paathyakram</p><p>₹1,234.50 on 4 दिसंबर 2026</p><button>Switch to Hindi</button></div>
Key points
Replace strings with keys and look them up through a provider or a library.
Use Intl.PluralRules or ICU syntax for plurals. Do not hard-code singular and plural.
Use Intl.NumberFormat and Intl.DateTimeFormat for values.
Never concatenate sentence fragments.
Set lang and dir, use logical CSS properties and plan for longer text.
Common mistakes
Building sentences by joining translated fragments.
Using count === 1 for plurals.
Formatting dates with manual string slicing instead of Intl.
Forgetting lang and dir on the document.
Hard-coding left and right in CSS for a layout that must flip.
Follow-ups
How would you lazy-load only the active locale file?
How do you handle right-to-left languages?
What does ICU message syntax let you express that plain templates cannot?
Tips
Mention Intl APIs first. They remove a lot of library need.
Use plurals as the example of why concatenation fails.
Raise layout issues (expansion, RTL) to show you think beyond strings.
63.react-0063Easyfresher
How do you implement form validation in plain React without a library?
Keep the field values in state, write a pure validate function that returns an errors object, and run it on submit (and optionally on blur for touched fields). Show errors next to fields, link them with aria-describedby, and block the submit when errors exist. Keep validation logic separate so it can be tested, and always validate again on the server.
Full answer
A form needs three things: values, errors and a moment when errors appear. Start with controlled inputs for the values. Then write validate(values), a plain function that returns an object such as { email: 'Enter a valid email' }. An empty object means valid. Because the function has no React in it, you can test it directly.
When to show errors is a user experience choice. Showing everything while the user is still typing is annoying. A common rule is to show an error after a field has been blurred (touched) or after a submit attempt. Keep a touched or submitted flag for that.
On submit: call event.preventDefault(), run validate, store the errors, and stop if there are any. If valid, send the data. Move focus to the first invalid field or to an error summary, so keyboard and screen reader users notice. Render each message in an element with an id, set aria-invalid on the input and link it with aria-describedby.
Derived values need no state. The errors can be calculated during render from the values: const errors = validate(values). Only store whether to show them.
Client checks are for convenience. A user can bypass them, so the server must validate again and return field errors that you show in the same place.
When forms grow, with many fields, arrays or async rules, move to React Hook Form or a similar library, plus a schema library such as Zod.
The example validates name and email and shows a success message.
The check submitted an empty form, then typed valid values and submitted again. Output of the run:
empty submit: Name is required | Enter a valid email
valid submit: Welcome, Asha
Key points
Controlled values plus a pure validate function returning an errors object.
Show errors after blur or submit, not on the first keystroke.
Use aria-invalid and aria-describedby, and move focus to the first error.
Derive errors from values. Store only whether they are visible.
Server validation is mandatory. Libraries help when forms get large.
Common mistakes
Validating only on the client.
Showing errors on every keystroke before the user finished typing.
Hiding errors from screen readers by not linking them to inputs.
Putting the validation rules inside the JSX handlers where they cannot be tested.
Keeping a copy of the errors in state that can drift from the values.
Follow-ups
How would you add an async check such as "email already used"?
How does React Hook Form change the amount of rendering a form does?
How would you share validation rules between client and server?
Tips
Describe the three pieces (values, errors, when to show) before coding.
Mention accessibility of errors. Many answers skip it.
Say you would move to React Hook Form for large forms.
64.react-0064Easyfresher
Write a useDebounce hook and use it to delay a search until the user stops typing.
useDebounce(value, delay) keeps a copy of the value in state and updates it only after the original has stopped changing for the delay. Inside an effect, start a setTimeout that sets the copy, and return a cleanup that clears the timer. Every new keystroke clears the previous timer, so only the last value is applied. Use the debounced value in the search effect or query.
Full answer
Typing "react" quickly fires five change events. Sending a request for each one is wasteful and can show out-of-order results. Debouncing waits until the input is quiet for a short time.
The hook is small. It holds debounced in state, initialised with the current value. An effect depends on value and delay. It starts setTimeout(() => setDebounced(value), delay) and returns () => clearTimeout(timer). When the value changes before the timer fires, React runs the cleanup first, which cancels the pending update, then the effect starts a fresh timer. After the user pauses, the timer fires once.
The component keeps two values: the raw input value for the text box, so typing feels instant, and the debounced value for the expensive work. A second effect, or a query keyed on the debounced value, performs the search. Because it depends only on the debounced value, it runs once per pause.
Choosing the delay: 200 to 400 milliseconds feels right for search. Do not debounce the input's own state, or the text box will lag.
Related ideas. Throttling limits how often something runs during a continuous event such as scroll, instead of waiting for it to stop. useDeferredValue is React's built-in way to lower the priority of rendering, but it does not delay network requests. A debounced search should also cancel in-flight requests when a new one starts.
The example logs each search to show it runs once per pause.
The check typed a, ab and abc in quick succession, then waited. The search ran once, for the final value. Output of the run:
right after typing: Typed: abc | Searching:
searching for abc
after the pause: Typed: abc | Searching: abc
Key points
Keep raw input state for the field and a debounced copy for expensive work.
The effect sets a timer and its cleanup clears it, so only the last value wins.
Typical delay for search is 200 to 400 milliseconds.
Debounce waits for quiet. Throttle limits frequency during a continuous event.
Cancel stale requests as well.
Common mistakes
Debouncing the input's own state so the text box lags.
Forgetting to clear the timer in the cleanup.
Leaving delay out of the dependency array.
Debouncing but not cancelling the previous request.
Confusing debounce with throttle.
Follow-ups
How would you write a useThrottle hook?
How is useDeferredValue different from debouncing?
How would you cancel a fetch started by an earlier search?
Tips
Explain the two values (raw and debounced) first.
Walk through what the cleanup does on each keystroke.
Contrast with throttle to show vocabulary.
65.react-0065Easyfresher
How do you handle text inputs, checkboxes, radio buttons and select elements in a React form with one change handler?
Store all values in one state object and give each field a name. A single handler reads the name and, for checkboxes, uses checked instead of value, then updates state with a computed key: setValues({ ...values, [name]: newValue }). Radio buttons share a name and compare checked to the stored value. A select takes value on the select element, not selected on options.
Full answer
Every form field has the same two parts in a controlled form: a value from state and an onChange that updates it. The details differ by type.
Text, email and textarea use value and event.target.value. In React, textarea takes value as well, not child text.
A checkbox is on or off. It uses checked={values.newsletter} and reads event.target.checked, which is a boolean. Using value for a checkbox is a common mistake.
Radio buttons are a group that shares one name. Each radio has its own value, and checked={values.slot === 'evening'} marks the active one. State stores the selected value as a string.
A select element takes value on the select itself, and the options carry only their own value. This is different from HTML, where selected is placed on an option. For multiple selection, set multiple and make value an array.
One handler can serve all fields. Give each input a name equal to the key in state. The handler picks the right property based on type: const value = type === 'checkbox' ? checked : value, then uses a computed property key. When updates may overlap, use the functional form of the setter so it does not rely on an old copy.
For large forms, the many re-renders per keystroke can matter. Uncontrolled inputs with FormData, or a library such as React Hook Form, avoid them. For small forms, the one-handler pattern is clear and enough.
The check typed a name, ticked the newsletter box, picked the evening batch and chose Maths. The pre element shows the state, rendered result: <form><label>Name <input value="Asha" name="name"></label><label><input type="checkbox" name="newsletter"> Newsletter</label><fieldset><legend>Batch</legend><label><input type="radio" value="morning" checked="" name="slot"> morning</label><label><input type="radio" value="evening" name="slot"> evening</label></fieldset><label>Course<select name="course"><option value="science">Science</option><option value="maths">Maths</option></select></label><pre>{"name":"Asha","newsletter":true,"slot":"evening","course":"maths"}</pre></form>
Key points
Controlled fields need a value from state and an onChange.
Checkboxes use checked and event.target.checked. Radios compare checked against the stored value.
Select uses value on the select element, not selected on options.
Use name plus a computed key for one handler across fields.
Large forms may benefit from uncontrolled inputs or a form library.
Common mistakes
Reading event.target.value for a checkbox and getting the string "on".
Putting selected on an option instead of value on the select.
Giving radios different names, so they are not a group.
Mutating the state object instead of copying it.
Forgetting name attributes when using one shared handler.
Follow-ups
How would you handle a select with multiple choices?
How would you validate this form on submit?
When would you switch to uncontrolled inputs or React Hook Form?
Tips
Mention the checkbox checked detail. It is the usual slip.
Use one example with all four types. It shows you know the differences.
Say you would reach for a library when forms grow.
66.react-0066Easyfresher
How do you set default values for props in React 19, and what happened to defaultProps and propTypes?
Use JavaScript default values in the destructured parameter: function Button({ size = 'md' }). React 19 removed defaultProps for function components and removed propTypes checking, so use default parameters and TypeScript instead. Defaults apply when the prop is undefined, not when it is null, which matters when passing null on purpose.
Full answer
A prop that the caller leaves out is undefined. Modern React handles defaults with plain JavaScript: function Button({ size = 'md', children }). The default is visible next to the code that uses it, works with TypeScript and needs no React feature.
In older React you could write Button.defaultProps = { size: 'md' } and Button.propTypes = { size: PropTypes.string }. React 19 stopped supporting both on function components. defaultProps on function components is ignored, so a component that relied on it receives undefined. Class components still support defaultProps. PropTypes checks were removed from the React package, so they no longer run. Use TypeScript for compile-time checks, or a runtime schema library such as Zod for data that comes from outside.
A subtle point: a default parameter applies for undefined only. If a caller passes null, the default is not used, and you need size ?? 'md' inside, or must decide that null is invalid. Another point: a default object or array in the parameter, such as items = [], creates a new value on every render. That can break memoization and effect dependencies, so use a constant defined outside the component when identity matters.
When migrating, search for .defaultProps and convert each to default parameters, then remove PropTypes imports or keep them only for documentation. The codemods in the React 19 upgrade guide help.
Also keep children optional with a default of nothing, and avoid default values that hide real bugs, such as a default user id.
The third button passes null, so the default is not used and data-size is not rendered at all. Rendered result: <section><h2>Untitled</h2><button data-size="md" data-items="0">Default size</button><button data-size="lg" data-items="0">Large</button><button data-items="0">Null size</button></section>
Key points
Use default parameters in the destructured props.
defaultProps on function components and propTypes checks no longer work in React 19.
Defaults apply only for undefined, not null.
A default array or object is a new value each render. Use an outer constant if identity matters.
Use TypeScript or a schema library for type checking.
Common mistakes
Relying on defaultProps in new function components after upgrading to React 19.
Expecting a default parameter to replace null.
Writing items = [] when the array is used as a dependency.
Keeping PropTypes and assuming they still check anything.
Using defaults that hide missing required data.
Follow-ups
How would you migrate a codebase that uses defaultProps everywhere?
How do TypeScript optional props relate to default parameters?
How would you treat null as "use the default"?
Tips
Mention the null versus undefined rule. It is the detail that shows care.
Show you know the React 19 change, not only the old API.
Offer TypeScript as the replacement for propTypes.
67.react-0067Easyfresher
Build an accordion where one section is open at a time. How do you model the state and make it accessible?
Store the id of the open section, or null, in one state variable. Clicking a header sets it to that id, or to null if it is already open. Render each header as a button with aria-expanded and aria-controls, and the panel only when open. Storing one id instead of a boolean per item guarantees a single open section and keeps the component simple.
Full answer
The state question decides the design. If each item had its own open boolean, the parent could not enforce "one at a time" without extra code. One openId in the parent does it by construction: it is either null or the id of the open section, so two sections can never be open together.
The header is a button, so it works with keyboard and screen readers. It gets aria-expanded={isOpen} and aria-controls pointing at the panel id. The panel has the matching id and is rendered only when open, or hidden with the hidden attribute if you want to keep its state.
The click handler toggles: setOpenId(isOpen ? null : id). If you need to allow several open sections, change the state to a Set or an array of ids and toggle membership immutably.
Extensions that come up in interviews. Make the component reusable by taking items as props. Support a default open item with an initial value. Add keyboard navigation between headers with arrow keys. Animate height with CSS grid or the hidden="until-found" attribute. Use native <details> and <summary> for simple cases, which gives the behaviour with no JavaScript, and a name attribute on details can group them into an exclusive accordion in current browsers.
IDs for aria-controls should be unique, so build them from the item id or use useId when the component can be rendered several times.
The check pressed each header once, so the last one is open and the others closed. Rendered result: <div><section><h3><button aria-expanded="false" aria-controls="panel-props">What are props?</button></h3></section><section><h3><button aria-expanded="false" aria-controls="panel-state">What is state?</button></h3></section><section><h3><button aria-expanded="true" aria-controls="panel-keys">Why keys?</button></h3><div id="panel-keys">They identify list items between renders.</div></section></div>
Key points
One openId state value enforces a single open section.
Headers are buttons with aria-expanded and aria-controls.
The click handler toggles between the id and null.
Use a set of ids for multiple open sections.
Native details and summary are a simple alternative.
Common mistakes
Keeping a boolean per item and letting several open together by accident.
Using div elements with click handlers as headers.
Forgetting aria-expanded, so screen readers cannot tell the state.
Using the array index as the id when the list can change.
Not allowing the open section to close again.
Follow-ups
How would you allow multiple sections open at once?
How would you add arrow-key navigation between headers?
When is the native details element enough?
Tips
Explain why one openId beats many booleans.
Include the ARIA attributes in the first version. It shows habits.
Mention details and summary as the zero-JavaScript option.
68.react-0068Easyfresher
What are the most common React errors beginners hit ("Too many re-renders", "Objects are not valid as a React child", missing keys), and how do you fix each one?
"Too many re-renders" means state is set during render, usually from onClick={setCount(1)} instead of a function. "Objects are not valid as a React child" means you rendered an object instead of a string or element. Key warnings mean a mapped list has no stable key. Hook errors mean a hook ran conditionally or outside a component. Read the message, find the line in the stack, and check what runs during render.
Full answer
Most beginner errors come from a small set of causes, and the messages point to them.
Too many re-renders. Calling a setter while rendering causes a new render, which calls it again. The usual cause is onClick={setCount(count + 1)}. The call runs immediately. Pass a function: onClick={() => setCount(count + 1)}. The same happens when you call a setter directly in the component body.
Objects are not valid as a React child. React can render strings, numbers, elements and arrays of them. A plain object, such as {user}, cannot be rendered. Render a field ({user.name}) or convert it (JSON.stringify). A Date also fails. Format it with toLocaleDateString.
Each child in a list should have a unique key. Add a stable key to the element returned from map. Do not use the index when items can reorder.
Rendered more hooks than during the previous render, or invalid hook call. Hooks must run in the same order each render, so no hooks inside conditions or loops, and only in components or custom hooks. Duplicate React copies in node_modules can also cause the invalid hook call error.
Cannot update a component while rendering a different component. One component's render calls another component's setter. Move that call into an effect or event handler.
Cannot read properties of undefined. Data has not arrived yet. Render a loading state or use optional chaining, but do not hide bad data silently.
Build a habit: read the first line of the message, then the first stack line from your own file, then check what runs during render. The example shows the corrected forms.
This file is the corrected version of each mistake. The wrong forms are described in the answer text. The check pressed both buttons. Rendered result: <div><button>Clicked 1</button><p>Asha joined on 1/15/2026</p><ul><li>Maths</li><li>Science</li></ul><button>Load</button><p>Score: 82</p></div>
Key points
Pass a function to onClick, not the result of calling a setter.
Render fields or strings, not objects or Date values.
Give list items stable keys.
Call hooks unconditionally at the top level of components and hooks.
Do not set one component's state during another component's render.
Common mistakes
Writing onClick={setCount(1)} and getting an infinite loop.
Rendering {object} directly in JSX.
Using the index as a key for items that can be reordered.
Calling a hook inside an if statement.
Reading a property of data that is still null.
Follow-ups
What causes "Invalid hook call" other than conditional hooks?
Why does React warn when you update a different component during render?
How do you read a React error stack to find the real cause?
Tips
Group errors by cause. It shows you understand them instead of memorizing messages.
Mention duplicate React copies for the invalid hook call message.
Say you read the first stack line in your own code.
69.react-0069Mediummid
How do you type useState, useRef, useReducer and context in TypeScript?
useState infers its type from the initial value, so add a generic only when the initial value is null or an empty collection: useState<User | null>(null). useRef takes the element type and starts with null for DOM refs. useReducer works best with a discriminated union of actions, which makes each case narrow correctly. Context is typed with createContext<Value | null>(null) and a custom hook that checks for null.
Full answer
TypeScript can infer most of this. You add annotations where the initial value does not tell the whole story.
useState: useState(0) is a number state. useState<User | null>(null) is needed because null alone would infer the type null. For an empty array, write useState<string[]>([]).
useRef has two shapes. For a DOM node, useRef<HTMLInputElement>(null) returns a ref object whose current is HTMLInputElement | null, so check for null before use or use optional chaining. For a mutable value, useRef<number>(0) gives a box you can write to.
useReducer: describe actions as a discriminated union, a set of object types distinguished by a literal type field:
type Action = { type: 'added'; name: string } | { type: 'removed'; id: number }.
Inside the reducer, a switch on action.type narrows the type, so action.name is only available in the added case. Add a never check in the default branch so a new action that is not handled becomes a compile error. dispatch is typed Dispatch<Action>.
Context: createContext<Value | null>(null) avoids a fake default value. A custom hook calls useContext and throws if it is null, which narrows the result to Value for every caller.
Event handlers and custom hooks follow the same ideas. Return tuples with as const or declare the return type so the tuple is not widened to an array.
Types do not exist at runtime, so validate data that comes from outside the app.
tsx
import { createContext, useContext, useReducer, useRef, useState, type Dispatch, type ReactNode } from 'react';
type Student = { id: number; name: string };
type Action = { type: 'added'; name: string } | { type: 'removed'; id: number };
function rosterReducer(state: Student[], action: Action): Student[] {
switch (action.type) {
case 'added':
return [...state, { id: state.length + 1, name: action.name }];
case 'removed':
return state.filter((s) => s.id !== action.id);
default: {
const unreachable: never = action;
throw new Error('Unhandled action: ' + JSON.stringify(unreachable));
}
}
}
type RosterContextValue = { students: Student[]; dispatch: Dispatch<Action> };
const RosterContext = createContext<RosterContextValue | null>(null);
function RosterProvider({ children }: { children: ReactNode }) {
const [students, dispatch] = useReducer(rosterReducer, []);
return <RosterContext value={{ students, dispatch }}>{children}</RosterContext>;
}
function useRoster(): RosterContextValue {
const value = useContext(RosterContext);
if (value === null) throw new Error('useRoster must be used inside RosterProvider');
return value;
}
function RosterEditor() {
const { students, dispatch } = useRoster();
const inputRef = useRef<HTMLInputElement>(null);
const [selected, setSelected] = useState<Student | null>(null);
function add() {
const name = inputRef.current?.value.trim();
if (name) dispatch({ type: 'added', name });
}
return (
<div>
<input ref={inputRef} defaultValue="Asha" />
<button onClick={add}>Add student</button>
<ul>
{students.map((s) => (
<li key={s.id}>
<button onClick={() => setSelected(s)}>{s.name}</button>
</li>
))}
</ul>
<p>Selected: {selected ? selected.name : 'none'}</p>
</div>
);
}
export default function App() {
return (
<RosterProvider>
<RosterEditor />
</RosterProvider>
);
}
The file passed the TypeScript compiler in strict mode and ran after the types were removed. The check pressed Add student and then the new name. Rendered result: <div><input value="Asha"><button>Add student</button><ul><li><button>Asha</button></li></ul><p>Selected: Asha</p></div>
Key points
Add a generic to useState only when the initial value is null or empty.
DOM refs are useRef<HTMLElement>(null) and current may be null.
Model reducer actions as a discriminated union and check exhaustiveness with never.
Type context as Value | null and add a hook that narrows it.
Use as const or an explicit return type for tuple-returning hooks.
Common mistakes
Writing useState(null) and then assigning an object, which fails to type check.
Forgetting that a DOM ref's current may be null.
Using string for the action type instead of literal types, which loses narrowing.
Giving the context a fake default object so a missing provider goes unnoticed.
Using the non-null assertion operator to silence errors that point to real bugs.
Follow-ups
What is exhaustiveness checking and why is it useful in reducers?
How would you type a custom hook that returns a tuple?
How do you derive TypeScript types from a runtime schema?
Tips
Show the discriminated union. It is the most useful TypeScript idea in React code.
Explain the null-context pattern in one sentence.
Mention that types do not validate runtime data.
70.react-0070Mediummid
How does React Hook Form work, and why is it often preferred over hand-written controlled forms for large forms?
React Hook Form registers inputs as uncontrolled fields and reads their values from the DOM, so typing does not re-render the whole form. useForm returns register, handleSubmit and formState. You spread register('email', rules) onto an input, call handleSubmit(onValid) on the form, and read errors from formState. It supports schema validators such as Zod, nested and array fields, and Controller for controlled third-party inputs.
Full answer
A hand-written controlled form re-renders the component on every keystroke, and each field needs state and a handler. For forms with dozens of fields this is slow to write and sometimes slow to run.
React Hook Form (RHF) keeps values in refs attached to the inputs. const { register, handleSubmit, formState: { errors } } = useForm() gives you the tools. register('email', { required: 'Email is required' }) returns props (name, ref, onChange, onBlur) that you spread on the input. RHF listens to the DOM and stores values without re-rendering the component on each change.
handleSubmit(onValid) wraps your submit handler. It prevents the default, runs validation, and calls onValid with the values only when everything passes. Otherwise it fills formState.errors, which you render next to the fields. Validation modes control when it runs: onSubmit (default), onBlur, onChange or onTouched.
Rules can be inline (required, minLength, pattern, validate) or come from a schema with a resolver, for example Zod through @hookform/resolvers. A schema gives one source of truth shared with the server and types derived from it.
Other features: defaultValues for initial data, reset after saving, setError for server-side errors, useFieldArray for dynamic lists, watch to react to values (it re-renders, so use it sparingly), and Controller to connect controlled components such as a custom select.
Trade-offs: the uncontrolled model needs care when a field value must drive other UI instantly, and a form library is one more dependency. For a login form of two fields, plain controlled inputs are fine.
The check submitted an empty form, then typed an email and an 8-character password and submitted again. Output of the run:
empty submit: Email is required | Password is required
valid submit: Signed up asha@example.com
Key points
RHF uses uncontrolled inputs and refs, so typing avoids whole-form re-renders.
register connects an input, handleSubmit validates and calls your handler.
Errors come from formState.errors. Validation can run on submit, blur or change.
Resolvers connect schema libraries such as Zod.
Use Controller for controlled components and useFieldArray for dynamic lists.
Common mistakes
Using watch for every field and losing the performance benefit.
Mixing register with a controlled value prop on the same input.
Not setting defaultValues, which leaves fields undefined.
Forgetting to show server-side errors with setError.
Treating client validation as a replacement for server validation.
Follow-ups
How does Controller differ from register, and when do you need it?
How would you connect a Zod schema as the resolver?
How would you build a dynamic list of fields with useFieldArray?
Tips
Explain the uncontrolled model. It is the reason RHF exists.
Name one limitation (instant dependent UI). It shows balance.
Mention schema validation shared with the server.
71.react-0071Mediummid
What problems does TanStack Query solve, and how do query keys, stale time and mutations with invalidation work?
TanStack Query manages server state: it fetches, caches by query key, deduplicates requests, refetches stale data in the background and tracks loading and error states. useQuery reads data identified by a key. Data is fresh for staleTime and stale afterwards. useMutation changes data on the server, and invalidateQueries marks related queries stale so they refetch and the UI updates.
Full answer
Writing fetches in effects means writing loading flags, error states, caching, retries and race protection each time. TanStack Query (formerly React Query) turns that into a few hooks and treats the API data as a cache owned by the server, not as client state.
useQuery({ queryKey: ['students'], queryFn }) runs the function and stores the result under the key. Components that use the same key share one request and one cache entry. The key is also the dependency list: ['student', id] is a different entry for each id, and changing id fetches the new one. Put every variable the function uses in the key.
The cache has two timers. staleTime says how long data counts as fresh (default 0, so data is stale at once). Stale data is still shown while a background refetch runs on triggers such as a new mount, window focus or reconnect. gcTime says how long unused entries stay in memory before removal. Raising staleTime reduces requests for data that rarely changes.
useQuery returns data, isPending, isError, error and isFetching, which separates the first load from background refreshes. Failed requests retry three times by default.
Mutations use useMutation({ mutationFn, onSuccess }). After a write, call queryClient.invalidateQueries({ queryKey: ['students'] }) so affected queries refetch. For instant feedback use optimistic updates with onMutate, rollback in onError, and invalidate in onSettled.
Client state such as an open modal does not belong in the query cache. Keep it in useState or a store. Setup requires a QueryClientProvider near the root.
The example uses an in-memory fake API so it runs without a network.
This used @tanstack/react-query with an in-memory fake API. The check waited for the first load, pressed Add Meera and waited for the refetch that invalidation triggers. Output of the run:
right after mount: AshaRaviAdd Meera
after the first fetch: AshaRaviAdd Meera
after the mutation and refetch: AshaRaviMeeraAdd Meera
Key points
Treat API data as a server-owned cache keyed by queryKey. Include every variable in the key.
staleTime controls freshness. gcTime controls how long unused data stays cached.
Data is shown stale while a background refetch runs.
useMutation writes data and invalidateQueries refreshes related reads.
Do not store client-only state in the query cache.
Common mistakes
Leaving a variable out of the query key, so the cache returns the wrong data.
Storing fetched data in useState and duplicating the cache.
Forgetting to invalidate after a mutation.
Using one huge key for everything instead of structured keys.
Putting client-only UI state in the query cache.
Follow-ups
How would you implement an optimistic update with rollback?
What is the difference between isPending and isFetching?
How does TanStack Query work with server rendering and prefetching?
Tips
Describe the cache and key model first. It explains every behaviour after.
Say that server state and client state differ. It shows design thinking.
Mention staleTime tuning as a practical lever.
72.react-0072Mediummid
What is Redux Toolkit, how do slices, the store and hooks fit together, and why is it preferred over classic Redux?
Redux Toolkit (RTK) is the official, standard way to write Redux. createSlice defines state, reducers and generated actions in one place, and lets you write updates that look like mutations because Immer turns them into immutable updates. configureStore builds the store with good defaults and devtools. Components use useSelector to read state and useDispatch to send actions, inside a Provider.
Full answer
Classic Redux needed action type constants, action creators, switch-based reducers and careful immutable updates, all in separate files. Redux Toolkit removes that ceremony while keeping Redux's single store, predictable updates and strong devtools.
createSlice({ name, initialState, reducers }) creates the pieces for one feature. Each reducer function receives the state and the action. Inside it you may write state.items.push(item), because Immer records the changes and produces a new immutable state. The slice returns the reducer and an actions object with a ready action creator for each reducer. The action type string is generated from the slice name and the reducer name.
configureStore({ reducer: { cart: cartSlice.reducer } }) combines slices, adds the Redux DevTools hookup and middleware that detects accidental mutation and non-serializable values in development.
In React, wrap the app in <Provider store={store}> from react-redux. Read state with useSelector((state) => state.cart.items.length). The component re-renders only when the selected value changes, so select the smallest piece you need. Send actions with useDispatch().
For async work, createAsyncThunk handles pending, fulfilled and rejected states, and listener middleware handles side effects. For server data, RTK Query (see its own question) is usually better than hand-written thunks.
When to choose RTK: large apps and teams that want conventions, middleware, time-travel debugging and a clear data flow. For small apps, useState, context or Zustand may be lighter.
The reducers look like they mutate state, but Immer produces new immutable state. The check pressed Add pen and then Clear, so the cart ends empty. Rendered result: <div><button>Add pen</button><button>Clear</button><p>0 items: </p></div>
Key points
createSlice produces reducers and action creators together. Immer lets you write mutating-style updates safely.
configureStore sets up the store, devtools and development checks.
Provider supplies the store. useSelector reads, useDispatch writes.
Select the smallest value you need to limit re-renders.
Use RTK Query for server data and thunks or listeners for other async work.
Common mistakes
Mutating state outside a slice reducer, where Immer does not protect you.
Selecting the whole state in useSelector and re-rendering on every change.
Returning a new value and mutating the draft in the same reducer.
Putting non-serializable values such as class instances in the store.
Using Redux for state that useState would handle.
Follow-ups
What does Immer do inside createSlice reducers?
How does createAsyncThunk model loading and error states?
When would you pick Zustand instead of Redux Toolkit?
Tips
Contrast with classic Redux boilerplate. It shows you know the history.
Explain the Immer point carefully. Many candidates say "RTK allows mutation".
Say what you would put in Redux and what you would leave out.
73.react-0073Mediummid
What is RTK Query, how do endpoints, generated hooks and tag invalidation work, and when do you pick it over TanStack Query?
RTK Query is the data fetching and caching tool inside Redux Toolkit. createApi defines endpoints (queries that read and mutations that write), and it generates hooks such as useGetStudentsQuery. Cache entries are keyed by endpoint and arguments. Queries declare providesTags, mutations declare invalidatesTags, and a matching mutation makes the right queries refetch. Choose it when the app already uses Redux Toolkit.
Full answer
RTK Query solves the same problem as TanStack Query: server state, caching, deduplication and loading flags. It lives in the Redux store, so the cache is visible in devtools and fits an existing Redux setup.
You define an API slice once with createApi. It takes a reducerPath, a baseQuery (usually fetchBaseQuery({ baseUrl }), or a custom function) and endpoints. Each endpoint is build.query for reads or build.mutation for writes. RTK Query generates hooks from the endpoint names: useGetStudentsQuery(args) and useAddStudentMutation().
The cache key is the endpoint name plus the serialized arguments. Two components calling useGetStudentQuery(5) share one request and one entry. Unused entries are removed after keepUnusedDataFor seconds (60 by default).
Tags connect reads and writes. A query declares providesTags: ['Student'] and a mutation declares invalidatesTags: ['Student']. When the mutation finishes, every active query that provides that tag refetches. Tags can include ids, such as { type: 'Student', id: 5 }, for fine-grained updates.
Setup needs the API reducer under api.reducerPath and api.middleware added to the store. The middleware handles caching, polling and invalidation.
Hooks return data, isLoading (first load), isFetching (any request), isError and error. Options include skip, pollingInterval and selectFromResult to avoid extra re-renders. For optimistic updates use onQueryStarted and updateQueryData.
Compared with TanStack Query: RTK Query is tied to Redux and comes with codegen from OpenAPI and good typing from endpoint definitions. TanStack Query works without Redux and has a larger ecosystem of patterns. If Redux is already in the project, RTK Query is the natural choice. If not, TanStack Query is lighter to adopt.
The example uses a custom baseQuery with in-memory data so it runs without a network.
This ran against a custom baseQuery and in-memory data. The check waited for the first load, pressed Add Meera and waited for the tag invalidation to refetch. Output of the run:
after first load: AshaRaviAdd Meera
after mutation and automatic refetch: AshaRaviMeeraAdd Meera
Key points
createApi defines endpoints and generates typed hooks.
The cache key is the endpoint plus its arguments, and requests are deduplicated.
providesTags and invalidatesTags drive automatic refetching after mutations.
The API reducer and middleware must be added to the store.
Pick it when Redux Toolkit is already in use. TanStack Query suits apps without Redux.
Common mistakes
Forgetting to add api.middleware to the store, so caching and invalidation do not work.
Mixing up isLoading and isFetching.
Skipping tags, so the list does not refresh after a mutation.
Putting the API data into another slice and keeping two copies.
Creating many small APIs instead of one API slice per backend.
Follow-ups
How would you do an optimistic update with onQueryStarted?
How do you inject endpoints from several files into one API?
What does selectFromResult do?
Tips
Compare with TanStack Query honestly. Both are good, and the decision depends on Redux.
Explain tags as the link between reads and writes.
Mention that the middleware is required.
74.react-0074Mediummid
Write a useFetch hook that handles loading and error states and cancels outdated requests when the URL changes or the component unmounts.
Keep data, error and loading state in the hook. In an effect that depends on the url, create an AbortController, pass its signal to fetch, and return a cleanup function that calls abort(). Ignore the AbortError in the catch block. The abort stops the old request from updating state, so a slow response for an old URL cannot overwrite a newer one. Accept the fetcher as an argument to make the hook testable.
Full answer
Without cancellation, a hook has a race condition. If the url changes from A to B and A is slower, A's response arrives last and the screen shows the wrong data.
The fix is in the effect. Each run creates its own AbortController. Its signal goes to fetch(url, { signal }). The cleanup function calls controller.abort(). React runs the cleanup before the next effect and on unmount, so an old request is aborted as soon as it is outdated. An aborted fetch rejects with an error named AbortError, which is not a real failure, so the catch block ignores it.
State handling: reset to a loading state when the url changes. Check response.ok, because fetch does not reject on 404 or 500 statuses. Parse JSON after that and set data.
A useful trick for testing and reuse is to accept the fetcher with a default: useFetch(url, fetcher = fetch). In tests or demos a fake can be passed in.
The abort pattern is still needed even when you use a flag such as let ignore = false in cleanup. The flag prevents stale state updates, and the abort also saves bandwidth and server work, and stops downloading bodies nobody wants.
In production, a library such as TanStack Query usually replaces this hook, adding caching, retries and deduplication. In interviews, writing the hook shows you understand effects, cleanup and races. The example uses a fake fetch where course 1 is slower than course 2, to prove that the older response is discarded.
The check clicked Course 1 (the slow one) and then Course 2 straight away. The requests for course 0 (the initial one) and course 1 were aborted, and only course 2 updated the screen. The final abort line is the unmount cleanup calling abort on a request that had already finished, which does nothing. Output of the run:
aborted /courses/0
aborted /courses/1
after both requests settled: Data for /courses/2
aborted /courses/2
Key points
Create an AbortController per effect run and abort in the cleanup.
Ignore AbortError. Treat other failures as errors.
Check response.ok because fetch does not reject on HTTP errors.
Reset loading state when the url changes.
Prefer a data library in production, but know this pattern.
Common mistakes
Not aborting or ignoring old responses, so a slow old request overwrites new data.
Treating AbortError as a user-visible error.
Forgetting response.ok and treating a 404 page as success.
Passing an inline fetcher function in the dependency array, which restarts the effect on every render.
Calling setState after unmount without protection in code that cannot abort.
Follow-ups
What other approach prevents stale updates besides aborting?
Why can the hook not be an async function passed to useEffect?
How would you add retries or caching, and why might you use TanStack Query instead?
Tips
Describe the race first, then the fix. It shows you know why.
Mention response.ok. Many candidates forget it.
Say a data library is the production answer.
75.react-0075Mediummid
Implement infinite scroll in React with IntersectionObserver, without scroll event handlers and without loading the same page twice.
Render a sentinel element after the list. In an effect, create an IntersectionObserver that calls loadMore when the sentinel becomes visible, and disconnect it in the cleanup. Track page, loading and hasMore in state, guard against concurrent loads, and remove the sentinel when there are no more pages. This avoids scroll listeners and layout reads, and stays efficient because the browser does the visibility work.
Full answer
A scroll event handler fires continuously and needs layout measurements. IntersectionObserver tells you asynchronously when an element enters the viewport and is the standard tool.
Design: the list shows items loaded so far. After the last item, an empty sentinel element sits in the DOM. An observer watches it. When it becomes visible, the component loads the next page and appends the items. Appending pushes the sentinel out of view, and the cycle repeats as the user scrolls.
State: items, page (or a cursor), loading and hasMore. The effect that creates the observer depends on the load function and the state it needs. Create the observer in the effect, observe the sentinel stored in a ref, and return observer.disconnect() as cleanup.
Correctness details. Guard re-entry: do nothing if loading is true or hasMore is false, so quick visibility changes cannot load the same page twice. Use functional updates when appending to avoid losing items. When the last page arrives, set hasMore to false and stop rendering the sentinel. Handle errors with a retry button so the user is not stuck. If the first page does not fill the screen, the sentinel is still visible and the observer fires again, so the screen fills without more code.
Extras: rootMargin: '200px' starts loading before the sentinel is visible, virtualization keeps the DOM small for thousands of rows, and cursor-based pagination is safer than page numbers when data changes. In a library-based app, TanStack Query's useInfiniteQuery manages pages, and the sentinel only calls fetchNextPage.
The example loads pages from a fake API of 25 items.
The runner has no layout, so the check used a small IntersectionObserver stand-in and called its callback to simulate the sentinel becoming visible. Output of the run:
first page: 0 items
after sentinel visible 1: 10 items
after sentinel visible 2: 20 items
after a third time: 25 items
sentinel still shown: false
Key points
Observe a sentinel after the list with IntersectionObserver instead of scroll listeners.
Create the observer in an effect and disconnect it in cleanup.
Guard against loading while already loading and after the last page.
Use rootMargin to prefetch and virtualization for very long lists.
Use cursor pagination and useInfiniteQuery in production.
Common mistakes
Using scroll events and reading layout values on every event.
Not guarding against concurrent loads, so a page loads twice.
Forgetting to disconnect the observer in cleanup.
Keeping the sentinel after the last page, so the observer keeps firing.
Rendering thousands of rows without virtualization.
Follow-ups
How would you add error handling and a retry button?
How would useInfiniteQuery change this code?
How would you keep scroll position and performance with 10,000 items?
Tips
Say why IntersectionObserver beats scroll handlers.
Show the guard against double loads. It is the bug interviewers look for.
Mention virtualization for long lists.
76.react-0076Mediummid
Build an accessible autocomplete input with keyboard navigation (arrow keys, Enter, Escape) and the right ARIA attributes.
Use an input with role="combobox", aria-expanded, aria-controls pointing at a listbox, and aria-activedescendant naming the highlighted option, so focus stays in the input while the highlight moves. Options have role="option" and aria-selected. Handle ArrowDown and ArrowUp to move the active index, Enter to pick, and Escape to close. Filter the list from the input value and reset the active index when the query changes.
Full answer
An autocomplete is a combobox. Keyboard and screen reader users need the same behaviour as mouse users.
Structure. The input has role="combobox", aria-expanded (true when the list is shown), aria-controls (the listbox id), aria-autocomplete="list" and aria-activedescendant (the id of the highlighted option). The popup is role="listbox" and each item is role="option" with an id and aria-selected for the highlighted one. Focus never leaves the input. aria-activedescendant tells assistive technology which option is current.
State: the query text, an activeIndex (-1 for none) and open. Filtered results are derived during render from the query, not stored in state.
Keyboard: ArrowDown moves to the next option and wraps or stops at the end, ArrowUp moves back, Enter selects the active option and closes the list, and Escape closes it (and may clear the text). Call preventDefault on arrow keys so the cursor in the input does not move. When the query changes, reset activeIndex and open the list.
Mouse: use onMouseDown on options with preventDefault to keep focus in the input, or onClick with care about blur order. Selecting sets the query to the chosen label.
For remote data, debounce the query, abort stale requests (see useFetch), and announce the number of results in a live region. Scroll the active option into view. Consider an existing accessible library such as Downshift, React Aria or Radix for production, because the details are easy to get wrong.
The check typed "ma" and then pressed ArrowDown twice and Enter. An asterisk marks the option with aria-selected set to true. Output of the run:
typed ma: options=[Maths, Machine learning, Marketing] value="ma" expanded=true
ArrowDown: options=[Maths*, Machine learning, Marketing] value="ma" expanded=true
ArrowDown again: options=[Maths, Machine learning*, Marketing] value="ma" expanded=true
Enter: options=[Machine learning] value="Machine learning" expanded=false
Key points
The input is a combobox with aria-expanded, aria-controls and aria-activedescendant. Focus stays in the input.
The popup is a listbox of role="option" items with aria-selected.
Handle ArrowUp, ArrowDown, Enter and Escape, and reset the active index when the query changes.
Derive the filtered list during render.
For remote data add debouncing, aborting and a live region announcement.
Common mistakes
Moving real focus into options, so typing stops working.
Forgetting preventDefault on arrow keys.
Not resetting the active index when the query changes.
Storing the filtered list in state instead of deriving it.
Missing ARIA attributes, so screen readers cannot follow the highlight.
Follow-ups
How would you load suggestions from a server with debounce and cancellation?
How would you announce the number of results to screen reader users?
Why might you use a library such as Downshift or React Aria here?
Tips
Name the combobox pattern and the aria-activedescendant technique.
Keep focus in the input. It is the central design decision.
Mention that a library is safer for production.
77.react-0077Mediummid
How do you build an accessible modal dialog in React that traps focus, closes on Escape and returns focus to the opener?
Render the dialog with role="dialog", aria-modal="true" and a label. When it opens, move focus inside (to the first control or the dialog itself). Handle Tab and Shift+Tab to cycle within the dialog, close on Escape, and on close restore focus to the element that opened it. The native dialog element with showModal() does most of this, so prefer it when you can, and mark the background inert.
Full answer
A modal must stop users from interacting with the page behind it. For keyboard and screen reader users that means four behaviours.
Move focus in. On open, focus the first focusable element or the dialog container (with tabIndex -1). Store document.activeElement before opening, so you can return later.
Trap focus. Tab on the last element goes to the first, and Shift+Tab on the first goes to the last. A keydown handler on the dialog finds the focusable elements with a selector and wraps.
Close with Escape, and also with a visible close button.
Restore focus. On close, focus the element that opened the dialog. Do this in an effect cleanup or after the state change.
Markup: role="dialog" (or "alertdialog"), aria-modal="true", and aria-labelledby pointing at the title. Render through a portal (createPortal to document.body) so stacking and overflow of parents do not interfere. Make the rest of the page inert so it cannot be focused or read while the dialog is open.
The native <dialog> element handles most of this. dialog.showModal() gives you focus management, a focus trap, Escape to close and an inert background. In React, use a ref and call showModal() in an effect when open becomes true. Use the native element when your browser support allows, and keep a library such as Radix Dialog or React Aria when you need more features, because custom traps miss edge cases such as shadow DOM, dynamic content and iframes.
The example implements the manual version to show the logic.
The dialog has three focusable controls: the coupon input, Enroll and Close. jsdom does not move focus on Tab, so the check sent each keydown to the dialog and moved focus itself only when the handler did not cancel the event, as a browser would. Then it pressed Escape. Output of the run:
after opening: focus on "Coupon code"
Tab: focus on "Enroll"
Tab again: focus on "Close"
Tab third time wraps: focus on "Coupon code"
Shift+Tab goes back to last: focus on "Close"
after Escape: focus on "Open dialog"
dialog in DOM: false
Key points
Move focus into the dialog on open and restore it to the opener on close.
Wrap Tab and Shift+Tab inside the dialog, and close on Escape.
Use role="dialog", aria-modal and aria-labelledby, and render in a portal.
Make the background inert while the dialog is open.
Prefer the native dialog element with showModal(), or a trusted library.
Common mistakes
Leaving focus on the page behind the dialog.
Not restoring focus to the opener on close.
Trapping focus with no Escape or close button.
Building a custom trap when the native dialog would work.
Missing aria-labelledby, so the dialog has no accessible name.
Follow-ups
How would the native dialog element simplify this component?
What does the inert attribute do and how does it help?
How would you handle nested dialogs?
Tips
List the four behaviours before coding. Interviewers check for them.
Mention the native dialog first, then explain the manual version.
Say you would use a tested library in production.
78.react-0078Mediummid
How do you announce dynamic changes (saved, errors, loading) to screen reader users in a React app?
Use a live region: an element with role="status" (polite) or role="alert" (assertive) that is already in the DOM before its text changes. Updating the text inside it makes screen readers announce the message without moving focus. Render the region always, even when empty, because a region that appears together with its content is often not announced. Move focus instead for navigation changes and form error summaries.
Full answer
Sighted users see a toast or a changed label. Screen reader users only hear what the page announces, so dynamic updates need a live region.
role="status" is equivalent to aria-live="polite": the message waits until the user is idle. Use it for saved messages, search result counts and progress. role="alert" is assertive and interrupts, so reserve it for errors and urgent notices. aria-live and aria-atomic can be set directly for more control.
The key rule: the region must exist in the DOM before the content changes. Browsers register live regions when the page loads or the element is added empty. A region that is conditionally rendered together with its text may be skipped. So render <p role="status">{message}</p> always, and change only the children. The container can be visually hidden with a "visually-hidden" CSS class when the message is only for assistive technology.
In React: keep the message in state, update it after the event, and clear it later if needed. Avoid announcing the same message twice in a row, because identical text may not trigger an announcement. Do not make large regions live, because every change will be read out.
Other patterns. Form validation: on submit with errors, either move focus to an error summary (with role="alert" or tabIndex -1) or focus the first invalid field, and use aria-invalid and aria-describedby on inputs. Route changes: single-page apps do not reload, so move focus to the main heading or announce the new page title. Loading: announce "Loading results" and the final count, and use aria-busy on the updating area.
Test with a real screen reader. Automated tools cannot check announcement behaviour.
jsx
import { useState } from 'react';
export default function SaveButton() {
const [status, setStatus] = useState('');
const [error, setError] = useState('');
function save(shouldFail) {
setError('');
setStatus('Saving...');
setTimeout(() => {
if (shouldFail) {
setStatus('');
setError('Could not save. Check your connection.');
} else {
setStatus('Saved at ' + new Date(Date.UTC(2026, 11, 4, 9, 30)).toISOString().slice(11, 16) + ' UTC');
}
}, 10);
}
return (
<div>
<button onClick={() => save(false)}>Save</button>
<button onClick={() => save(true)}>Save (fails)</button>
<p role="status">{status}</p>
<p role="alert">{error}</p>
</div>
);
}
Both regions are always rendered and only their text changes, which is the important detail. The check pressed Save and the failing button. Rendered result: <div><button>Save</button><button>Save (fails)</button><p role="status"></p><p role="alert">Could not save. Check your connection.</p></div>
Key points
Use role="status" for polite messages and role="alert" for urgent ones.
Render the live region before changing its text.
Move focus for route changes and error summaries instead of using a live region only.
Keep regions small and avoid repeating identical messages.
Test with a screen reader because automation cannot verify speech.
Common mistakes
Rendering the live region together with its message, so it is not announced.
Using role="alert" for routine messages and interrupting the user.
Making a whole page section live.
Relying on color alone to show an error.
Assuming that automated tests prove announcements work.
Follow-ups
What is the difference between aria-live polite and assertive?
How do you manage focus after a route change in a single-page app?
How would you build an error summary for a long form?
Tips
State the "region must exist first" rule. It is the most useful fact.
Match politeness to urgency.
Mention testing with NVDA, VoiceOver or JAWS.
79.react-0079Mediummid
How do you expose a child's DOM node or methods to a parent in React 19, and what changed about forwardRef?
In React 19, function components receive ref as an ordinary prop, so forwardRef is no longer needed: function Input({ ref, ...props }) { return <input ref={ref} {...props} /> }. forwardRef still works but is deprecated and will be removed later. To expose a limited API instead of the raw node, call useImperativeHandle(ref, () => ({ focus, clear })), so the parent can call methods without reaching into the DOM.
Full answer
A ref normally attaches to a DOM node or class instance. Passing ref to your own function component did not work before React 19, because ref was not a prop. forwardRef was the wrapper that received it as a second argument.
In React 19 for function components, ref is a regular prop: function Input({ ref, ...props }). Pass it down to a DOM element and the parent's ref points to that element. Code that used forwardRef continues to work, and React ships codemods to remove it. forwardRef is expected to be deprecated and removed in a future version. Class components do not receive ref as a prop, because it refers to the class instance.
Often you do not want to expose the entire DOM node. useImperativeHandle(ref, createHandle, deps) lets the child decide what the parent gets: an object such as { focus() {}, clear() {} }. The parent writes inputRef.current.focus() and cannot touch the other node properties. This keeps the child's internals private and the API small. Pass dependencies when the handle uses changing values.
Use imperative handles sparingly, for things that are naturally commands: focus, scroll to, play, pause, reset. Anything that can be expressed with props and state should be, because imperative code is harder to follow. Inputs that need clear are usually better as controlled components with the parent owning the value.
React 19 also lets a ref callback return a cleanup function, which runs when the element is detached, replacing the pattern of calling the callback with null. The TypeScript type for a ref prop is Ref<HTMLInputElement>, or use ComponentProps<'input'> that already includes it.
The parent only sees focus and clear, not the input element. The check set a value, pressed Focus, and then pressed Clear. Output of the run:
after Focus: input focused = true
after Clear: input value = ""
Key points
In React 19, ref is a regular prop for function components, so forwardRef is not needed.
forwardRef still works for now and is slated for removal.
useImperativeHandle exposes a small custom API instead of the raw DOM node.
Use imperative handles for commands, and props and state for everything else.
Ref callbacks can return a cleanup function in React 19.
Common mistakes
Still wrapping every component in forwardRef in new React 19 code.
Exposing the whole DOM node when a small API is enough.
Using imperative methods for things that props and state can express.
Forgetting that class components do not take ref as a prop.
Reading ref.current during render.
Follow-ups
How do you type a ref prop in TypeScript?
What does a ref callback cleanup function do in React 19?
When is useImperativeHandle a code smell?
Tips
State the React 19 change first, then the legacy form. Interviewers still ask about forwardRef.
Show you prefer props over imperative handles.
Give focus and scroll as the good use cases.
80.react-0080Mediummid
How does useTransition work in React 19, including async transitions, and what are its limits?
useTransition returns [isPending, startTransition]. State updates inside startTransition are marked non-urgent: React can interrupt them for urgent updates such as typing, and keeps showing the old UI while the new one renders. In React 19 the function may be async, so isPending stays true during awaited work. State updates after an await must be wrapped in another startTransition. Transitions cannot control text inputs and do not make slow code faster.
Full answer
React 18 introduced transitions. const [isPending, startTransition] = useTransition() gives a flag and a function. Updates inside startTransition(() => setTab('reports')) are low priority: if something urgent happens, such as a keystroke, React handles that first and can restart or drop the transition render. While the transition renders, the current UI stays on screen, and Suspense does not replace it with a fallback if the content is already visible. isPending lets you show a subtle indicator.
React 19 added async functions: startTransition(async () => { ... }). React keeps isPending true until the promise settles, which covers loading and saving. This is the foundation for Actions: forms, useActionState and useOptimistic work on top of it.
The limit to remember: React tracks transition updates only until the first await. A state update after an await runs outside the transition unless you wrap it again with startTransition. Write await load(); startTransition(() => setTab(next));. This is a known limitation of the current implementation. Errors thrown in the function propagate to the nearest error boundary.
What transitions are not: they do not debounce, they do not make slow components faster, and they do not work for controlled input values, because those must update synchronously or the text jumps. For the latter, use the same transition on a derived state, or useDeferredValue for a value you receive. A transition helps when an update causes heavy rendering. The long task is still there, but React yields between units of work so the input stays responsive.
The standalone startTransition import works outside components, but gives no isPending.
The example switches tabs after a simulated data load.
The check pressed Reports and read the text right away, and again after the simulated load. Output of the run:
start: OverviewReportsTab: Overview
right after the click: OverviewReportsTab: Overview (loading)
after the data arrived: OverviewReportsTab: Reports
Key points
Transition updates are non-urgent, interruptible and keep the old UI visible.
isPending shows that a transition is in progress.
In React 19 async functions are supported and isPending stays true until they finish.
Updates after an await need another startTransition.
Transitions do not speed up slow code and are not for controlled input values.
Common mistakes
Setting state after an await without wrapping it in startTransition.
Using a transition for the text of a controlled input.
Expecting a transition to make a slow render faster.
Reading isPending as a loading state for a Suspense fallback.
Calling startTransition and then also showing a separate manual loading flag.
Follow-ups
What is the difference between useTransition and useDeferredValue?
How do transitions interact with Suspense boundaries?
How do Actions in React 19 build on transitions?
Tips
Mention the await limitation. It separates people who used the API from people who read about it.
Say transitions are scheduling, not performance magic.