React Roadmap
React is one of the most widely used libraries for building interactive web interfaces out of small, reusable components, and its model carries over to mobile through React Native. Front-end, full-stack and many product engineering roles expect it, and interviews test both what you can build and whether you understand what React does under the hood.
This roadmap goes from your first component to the topics senior interviews cover: rendering, effects, state architecture, data fetching, testing, performance and server rendering. Each topic has a short example and an exercise, in the order the ideas build on each other. Core items are expected of every React developer, recommended items are common in real jobs, and optional items can wait.
By the end you will be able to build and test a production-quality app and explain your design choices. Practise in coding practice and track your progress in progress page.
- Level
- Beginner to advanced
- Time
- 14–20 weeks at about 8 hours a week, less if you already know modern JavaScript well
- Scope
- 57 topics in 10 stages
- Before you start
- Modern JavaScript Roadmap: functions, arrow functions, destructuring, spread, modules, array methods such as
mapandfilter, promises andasync/await; Basic HTML Roadmap: semantic elements, forms and attributes; Basic CSS Roadmap: selectors, the box model and Flexbox; Comfort with the terminal, npm and Git and GitHub Roadmap
What you will be able to do
- Build multi-page React apps from scratch with components, hooks, routing and forms.
- Explain how React renders and when components re-render.
- Choose the right home for each kind of state: local, shared, server, URL or form state.
- Fetch, cache and mutate server data correctly, including loading, error and race conditions.
- Diagnose performance problems with the profiler and fix them with memoisation, transitions and code splitting.
- Explain server rendering, hydration and Server Components, and pick a framework for a project.
The roadmap at a glance
- Stage 1Foundations: Components, JSX and PropsBeginner · 1–2 weeks · 8 topics
- Stage 2State and InteractivityBeginner · 1–2 weeks · 6 topics
- Stage 3Rendering, Effects and Core HooksIntermediate · 2 weeks · 7 topics
- Stage 4Reusable Patterns and Resilient UIIntermediate · 1–2 weeks · 6 topics
- Stage 5Styling, UI Libraries and AccessibilityIntermediate · 1 week · 5 topics
- Stage 6Routing, Data Fetching and FormsIntermediate · 2–3 weeks · 5 topics
- Stage 7State Management at ScaleIntermediate · 1–2 weeks · 4 topics
- Stage 8TypeScript and TestingIntermediate · 2 weeks · 5 topics
- Stage 9Performance and Concurrent RenderingAdvanced · 1–2 weeks · 5 topics
- Stage 10Server Rendering, Frameworks and BeyondAdvanced · 2–3 weeks · 6 topics
Stage 1 Foundations: Components, JSX and Props
Goal. Set up a React project and build static, data-driven screens from small components.
How React Works Core
With React you describe, as a tree of components, what the screen should look like for the current data, and React works out the DOM changes. This is declarative UI: no appendChild or class toggling by hand.
A useful mental model is UI = f(state). When data changes, React calls your component functions again, compares the new output with the previous one (reconciliation) and applies only the differences to the real DOM. The in-memory description is often called the virtual DOM.
React is a library, not a full framework: react-dom renders it to the browser, and routing, data fetching and styling come from your own choices or a framework.
Practice. Explain in writing what happens between a button click and the screen changing.
Project Setup with Vite and CLI Tools Core
Start single-page projects with Vite. It gives you a fast dev server with hot reload, TypeScript and JSX support, and an optimised production build.
npm create vite@latest my-app -- --template react-ts
cd my-app && npm install
npm run dev # dev server with hot reload
npm run build # production bundle in dist/Create React App, the old default starter, is deprecated. Do not start new projects with it. If you need routing and server rendering built in, start from a framework such as Next.js.
Add ESLint with the React hooks plugin, Prettier, and the React Developer Tools browser extension.
Practice. Create a Vite React TypeScript project, delete the demo code, and render a heading that shows today's date.
JSX Core
JSX lets you write markup inside JavaScript. The build step compiles <h1>Hi</h1> into a plain function call, so JSX is JavaScript, not HTML. The rules that trip people up:
- Put any JavaScript expression inside curly braces:
{user.name}. - Use
classNameinstead ofclassandhtmlForinstead offor; most attributes are camelCase, such asonClickandtabIndex. styletakes an object, which is why you see double braces:style={{ marginTop: 8 }}.- Return one root element; wrap siblings in a fragment
<>...</>. - Close every tag, including
<img />and<input />.
const card = (
<>
<img className="avatar" src={user.avatar} alt="" />
<p>Hello, {user.name}</p>
</>
);React escapes values in braces, which blocks most cross-site scripting. dangerouslySetInnerHTML turns that off, so use it only with sanitised HTML.
Practice. Convert a small static HTML profile card into JSX and fix every attribute that differs.
Functional Components Core
A component is a function that returns JSX. Its name must start with a capital letter, because lowercase tags such as <div> are treated as HTML elements. Pages are built by nesting components into a tree.
function Avatar({ url, size = 48 }) {
return <img src={url} width={size} height={size} alt="" />;
}
export default function Profile() {
return <section><Avatar url="/me.png" /><h2>Jordan Lee</h2></section>;
}Components must be pure while rendering: same props and state, same JSX, and no changes to outside variables, no API calls and no DOM access. Side effects belong in event handlers or effects. Never define a component inside another component; it gets a new identity on every render and loses its state.
Older code uses class components with a render() method. Learn to read them, but write functions.
Practice. Split a page mock-up into a component tree on paper, then build it with at least five components.
Props Core
Props are the inputs a parent passes to a child, written like HTML attributes and received as one object. They can be any value, including functions and JSX.
function Button({ variant = 'primary', onClick, children }) {
return (
<button className={`btn btn-${variant}`} onClick={onClick}>
{children}
</button>
);
}
<Button variant="danger" onClick={deleteItem}>Delete</Button>Props are read-only: a component must never change its own props. If a value needs to change, it belongs in state somewhere. The special children prop holds whatever is nested between the tags, which is how cards, modals and layouts wrap arbitrary content.
Practice. Build a Card component that takes title, an optional footer and children, and use it three times.
Conditional Rendering Core
JSX is JavaScript, so conditional rendering uses normal JavaScript: an if with an early return for whole alternative views, a ternary to choose between two pieces of UI, && to show something only when a condition holds, and return null to render nothing.
function Inbox({ messages, isLoading }) {
if (isLoading) return <Spinner />;
return (
<div>
{messages.length > 0 && <Badge count={messages.length} />}
{messages.length === 0 ? <p>No mail</p> : <List items={messages} />}
</div>
);
}Watch out for {count && <Badge />}: when count is 0, React renders the number 0. Compare explicitly so the left side is always a boolean.
Practice. Build a Notification that styles success, warning and error differently and renders nothing without a message.
Lists and Keys Core
Render a collection by mapping an array to JSX. Each item needs a key that is unique among its siblings and stable across renders, usually an ID from your data.
<ul>
{todos.map(todo => <TodoItem key={todo.id} todo={todo} />)}
</ul>Keys tell React which item is which between renders. With the array index as key, identity is tied to position: after an insert, delete or sort, state such as a typed input value stays at the old position and appears on the wrong item. Index keys are safe only for static lists.
Never create keys with Math.random() during render; every render then destroys and recreates every item. Changing a key on purpose resets a component's state, for example <Form key={userId} />.
Practice. Render a sortable list of editable inputs with index keys, sort it, observe the bug, then fix it with real IDs.
Events Core
Attach handlers with camelCase props such as onClick, onChange and onSubmit. Pass a function, not a call: onClick={handleClick} is right, while onClick={handleClick()} runs during render.
function Search({ onSearch }) {
function handleSubmit(e) {
e.preventDefault(); // stop the page reload
onSearch(e.target.query.value);
}
return <form onSubmit={handleSubmit}><input name="query" /></form>;
}React passes a synthetic event that behaves the same in every browser. Events bubble up the tree; e.stopPropagation() stops them. To pass arguments, wrap the call: onClick={() => remove(item.id)}.
Practice. Build a colour picker with selectable swatches and a reset button, passing handlers down as props.
Stage 2 State and Interactivity
Goal. Make components remember and change data, keep forms in sync with state, and share state between components.
useState Hook Core
The useState hook gives a component memory between renders. It returns the current value and a setter; calling the setter asks React to render again with the new value.
const [count, setCount] = useState(0);
function addThree() {
setCount(c => c + 1); // updater form reads the latest value
setCount(c => c + 1);
setCount(c => c + 1);
}Each render sees a snapshot of state. Writing setCount(count + 1) three times adds only one, because all three read the same count. Use the updater form when the next value depends on the previous one. React batches updates from the same event into one render. For an expensive initial value pass a function, useState(() => load()), so it runs only once.
Practice. Build a like button that toggles and shows a count, and explain why the updater form matters for rapid clicks.
Updating Objects and Arrays Immutably Core
Treat state as read-only. To change an object or array, create a new one. React detects changes by comparing references with Object.is, so mutating the old object and setting it again often does nothing.
setUser(u => ({ ...u, email: newEmail }));
setTodos(t => [...t, newTodo]); // add
setTodos(t => t.filter(x => x.id !== id)); // remove
setTodos(t => t.map(x => x.id === id ? { ...x, done: true } : x));Avoid push, splice, sort and reverse on state, or apply them to a copy ([...items].sort() or toSorted()). Spreading is shallow, so copy every nested level you change. For deep updates, Immer lets you write mutating-style code that produces a new value.
Practice. Write add, change-quantity and remove functions for a shopping cart that never mutate the original array.
Props vs State Core
Props vs state is a classic first interview question. Both are plain data that affect rendering; they differ in ownership.
| Props | State |
|---|---|
| Passed in by the parent | Owned by the component |
| Read-only in the child | Changed with its setter |
| Like function arguments | Like private memory |
A change to either causes a re-render, and a parent's state often becomes a child's props.
Keep state minimal. If a value can be calculated from props or other state, such as a filtered list or a full name, compute it during render. Duplicated state drifts out of sync and causes many common bugs.
Practice. Take a component that stores firstName, lastName and fullName in state and remove the redundant state.
Lifting State Up and One-Way Data Flow Core
Data flows down: parents pass values to children through props. When two siblings need the same data, move the state to their closest common parent, pass the value down, and pass a callback down so children can request changes.
function Accordion({ panels }) {
const [openId, setOpenId] = useState(null);
return panels.map(p => (
<Panel key={p.id} title={p.title} isOpen={openId === p.id}
onToggle={() => setOpenId(openId === p.id ? null : p.id)} />
));
}Each piece of state should have one owner, a single source of truth. When lifting forces you to pass props through layers that do not use them (prop drilling), use composition with children or context instead.
Practice. Build an accordion where only one panel can be open at a time, with the state held in the parent.
Forms Core
A controlled input takes its value from state and reports changes through onChange, so state is always the source of truth. Validation and conditional fields become simple.
const [email, setEmail] = useState('');
return (
<form onSubmit={e => { e.preventDefault(); save(email); }}>
<label htmlFor="email">Email</label>
<input id="email" value={email} onChange={e => setEmail(e.target.value)} />
<button disabled={!email.includes('@')}>Sign up</button>
</form>
);Uncontrolled inputs keep their value in the DOM: set defaultValue and read values on submit with new FormData(form). That means less code and fewer renders. Checkboxes use checked. In React 19 a function passed to <form action> receives the FormData directly. Large forms usually move to a form library.
Practice. Build a registration form with a text field, a select and a checkbox, plus inline validation.
Composition vs Inheritance Recommended
On composition vs inheritance React is clear: build complex components by combining simpler ones, not by extending base classes. Function components make inheritance hierarchies impractical anyway.
function Dialog({ title, actions, children }) {
return (
<div role="dialog" aria-label={title}>
<h2>{title}</h2>
{children}
<footer>{actions}</footer>
</div>
);
}The children prop lets a container wrap any content, and props that take JSX act as named slots, such as actions above. A DangerButton simply renders a Button with fixed props. Passing ready-made JSX down also cuts prop drilling, because the middle layers never see the data. Share non-visual logic through custom hooks.
Practice. Build a Layout with sidebar and children slots and use it on two pages.
Stage 3 Rendering, Effects and Core Hooks
Goal. Explain exactly when and why components render, and use effects, refs, context and reducers without common bugs.
Rendering and Reconciliation Core
Rendering in React has three steps. A trigger (first mount or a state update) schedules work. In the render phase React calls your components to get new JSX. In the commit phase it applies the minimal DOM changes and then runs effects.
A component renders again when its state changes, when its parent renders, or when a context it reads changes. By default all children render with their parent, even if their props did not change. That is usually fast.
React compares trees by element type and position. Same type at the same position keeps the component and its state; a different type or key mounts a fresh one. In development, <StrictMode> renders twice to expose impure code.
Practice. Log renders in a parent and three children, change parent state, and predict the output before you look.
Component Life Cycle Core
Every component has a component life cycle: it mounts, updates any number of times, and unmounts. Class components had a method per phase, and you will meet them in older code:
| Class method | Hook equivalent |
|---|---|
componentDidMount | useEffect(fn, []) |
componentDidUpdate | useEffect(fn, [deps]) |
componentWillUnmount | the effect's cleanup function |
shouldComponentUpdate | React.memo |
With hooks, think in synchronisation rather than life-cycle events. An effect says: keep this external thing in sync with these values. React starts it after mount, restarts it when dependencies change, and stops it on unmount.
Practice. Rewrite a class component that subscribes to window resize in componentDidMount as a function component.
Rules of Hooks Core
Hooks are functions whose names start with use, and they follow two rules:
- Call them only at the top level of a component or custom hook, never inside conditions, loops, nested functions or after an early return.
- Call them only from function components or other custom hooks.
React matches hook data by call order, so a hook skipped on one render makes every later hook read the wrong slot.
// wrong: the hook disappears when isOpen is false
if (isOpen) { const [x, setX] = useState(0); }
// right: always call it, then branch
const [x, setX] = useState(0);
if (!isOpen) return null;The ESLint hooks plugin enforces both rules.
Practice. Turn on the hooks lint rules in your project and fix every warning without disabling a rule.
useEffect Hook Core
The useEffect hook synchronises a component with something outside React, such as a subscription, timer, socket or third-party widget. It runs after the commit, so it does not block painting.
useEffect(() => {
const conn = connect(roomId);
return () => conn.close(); // cleanup
}, [roomId]); // re-run when roomId changesThe dependency array lists every reactive value the effect reads: no array runs after every render, [] runs after mount only, [roomId] runs when roomId changes. Cleanup runs before the next run and on unmount. In development StrictMode mounts, unmounts and mounts again, so missing cleanup shows up at once.
Do not use an effect to derive values or to react to a user action; do those during render or in the handler.
Practice. Show the window width and update it on resize, with cleanup, and confirm no listeners leak under StrictMode.
useRef and Refs Core
The useRef hook returns a mutable object, { current }, that persists between renders. Changing ref.current does not cause a render, so refs suit values that do not affect output, such as timer IDs. Their most common use is reaching a DOM node:
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
</>
);In React 19 function components accept ref as a normal prop; older code uses forwardRef for the same thing. useImperativeHandle exposes a limited API instead of the raw node. Do not read or write refs during render. If the screen should change when a value changes, it belongs in state.
Practice. Build a stopwatch with the interval ID in a ref and elapsed time in state, and explain each choice.
Context and useContext Core
Context passes data deep into the tree without threading props through every level. It suits values many components need: current user, theme, locale.
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('dark');
return <ThemeContext value={theme}><Toolbar /></ThemeContext>;
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>Save</button>;
}Older code writes ThemeContext.Provider. Every consumer re-renders when the value changes, so an object literal such as value={{ user, setUser }} re-renders all consumers on every render; wrap it in useMemo or split contexts. Context transports values; it is not a state manager by itself.
Practice. Add light and dark themes with context, including a toggle inside a deeply nested settings menu.
useReducer Recommended
The useReducer hook moves update logic into a pure reducer function: (state, action) => nextState. It fits state with several related fields or many kinds of update, and reducers are easy to unit test.
function reducer(state, action) {
switch (action.type) {
case 'added': return [...state, action.todo];
case 'toggled': return state.map(t => t.id === action.id ? { ...t, done: !t.done } : t);
case 'deleted': return state.filter(t => t.id !== action.id);
default: throw new Error('Unknown action ' + action.type);
}
}
const [todos, dispatch] = useReducer(reducer, []);Handlers describe what happened; the reducer decides the new state. dispatch is stable, so a reducer plus context covers much shared state without a library.
Practice. Convert a todo list built with several useState calls to useReducer and unit test the reducer.
Stage 4 Reusable Patterns and Resilient UI
Goal. Share logic between components, render outside the normal tree, and handle loading and error states gracefully.
Writing Custom Hooks Core
Writing custom hooks is how you share stateful logic. A custom hook is a function named use... that calls other hooks. Each component that calls it gets its own state; hooks share logic, not data.
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key);
return saved !== null ? JSON.parse(saved) : initial;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}Give each hook one purpose and a clear name, such as useOnlineStatus. Extract one when the same state-plus-effect pattern appears twice.
Practice. Write useDebouncedValue(value, delay) and use it so a search box calls the API only after typing pauses.
Hooks Best Practices Core
Most hook bugs come from a few habits. These hooks best practices avoid them:
- Derive values during render instead of copying props into state with an effect.
- Put user-triggered logic in event handlers, not in effects that watch a flag.
- List dependencies honestly. If the list feels wrong, restructure: move the function inside the effect or use the updater form.
- Watch for stale closures: a callback that captured old state keeps seeing it.
- Add
useMemoanduseCallbackafter measuring, not by default.
Interviewers look for exactly these habits.
Practice. Review an old component of yours and remove one unnecessary effect and one piece of redundant state.
High Order Components and Render Props Recommended
Before hooks, logic was shared with two patterns you will still meet in older code and some libraries.
A higher-order component, often written high order components or HOCs, wraps a component and returns an enhanced version. Redux's connect is a well-known example.
function withAuth(Component) {
return function Protected(props) {
const user = useUser();
return user ? <Component {...props} user={user} /> : <Navigate to="/login" />;
};
}With render props, a component receives a function, usually as children, and calls it with its internal state so the caller controls the markup: <Mouse>{pos => <p>{pos.x}</p>}</Mouse>.
Both add wrapper nesting and hide where props come from. Prefer custom hooks in new code.
Practice. Write a withLogger HOC that logs mounts, then rewrite it as a useLogMount hook and compare.
Portals Recommended
A portal renders children into a different DOM node while keeping them in the same place in the React tree. It is the standard tool for modals, tooltips and toasts that must escape a parent with overflow: hidden or a low z-index.
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
return createPortal(
<div className="backdrop" onClick={onClose}>
<div role="dialog" aria-modal="true">{children}</div>
</div>,
document.body
);
}Context and event bubbling still follow the React tree. A real modal also needs focus moved in, trapped while open, Escape to close and focus restored afterwards.
Practice. Build a modal with a portal that closes on Escape and returns focus to the button that opened it.
Error Boundaries Core
If a component throws while rendering, React unmounts the whole tree and users see a blank page. Error boundaries catch these errors in their subtree and show a fallback.
class ErrorBoundary extends React.Component {
state = { error: null };
static getDerivedStateFromError(error) { return { error }; }
componentDidCatch(error, info) { logError(error, info.componentStack); }
render() {
return this.state.error ? <p>Something went wrong.</p> : this.props.children;
}
}They must still be class components; many teams use the react-error-boundary package, which adds reset support. They do not catch errors in event handlers, async code outside rendering, or server rendering; use try/catch there. Wrap each route and independent widget so one failure does not take down the page.
Practice. Wrap two dashboard widgets in separate boundaries, make one throw, and add a retry button that resets it.
Suspense and Lazy Loading Core
<Suspense> shows a fallback while something inside it is not ready. Its first use is code splitting: lazy loads a component's code only when it first renders.
const Settings = lazy(() => import('./Settings'));
<Suspense fallback={<Spinner />}>
<Settings />
</Suspense>Suspense also works for data when the source supports it: frameworks such as Next.js, libraries such as TanStack Query and Relay, and the use API reading a promise. A waiting component suspends and the nearest boundary shows its fallback.
Nested boundaries let a page show its shell first and fill in slower parts later.
Practice. Lazy-load three routes and confirm in the Network tab that each chunk loads on demand.
Stage 5 Styling, UI Libraries and Accessibility
Goal. Style components in a maintainable way, build accessible UI, and choose UI and animation libraries for clear reasons.
Styling Approaches and CSS Modules Core
Plain global CSS works, but in large apps class names collide. CSS Modules fix this at no runtime cost: any *.module.css file is scoped at build time and imported as an object.
/* Button.module.css */
.primary { background: navy; color: white; }
// Button.jsx
import styles from './Button.module.css';
export const Button = props => <button className={styles.primary} {...props} />;Runtime CSS-in-JS libraries such as styled-components and Emotion are common in existing code, but they cost performance and fit poorly with Server Components. Zero-runtime tools such as Panda CSS keep typed style objects and extract static CSS at build time. Use clsx for conditional class names.
Practice. Style a card with a CSS Module, including hover and dark-mode states.
Tailwind CSS Recommended
Tailwind CSS is utility-first: you compose small single-purpose classes in JSX, and the build generates only the CSS you use.
function Alert({ type, children }) {
const tone = type === 'error' ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800';
return <div role="alert" className={`rounded-lg p-4 text-sm ${tone}`}>{children}</div>;
}Benefits: no naming, no unused CSS, consistent spacing and colour scales, and styles next to the markup. Costs: long class strings, a vocabulary to learn, and the discipline to turn repeated patterns into components. Write complete class names; partial strings like bg-${tone}-500 are not detected by the build.
Practice. Rebuild the CSS Module card in Tailwind and compare readability.
Component Libraries: Styled and Headless Recommended
Styled component libraries such as Material UI, Chakra UI and Mantine give you finished buttons, dialogs, tables and date pickers. They speed up admin tools but add bundle weight and a recognisable look.
Headless component libraries provide behaviour and accessibility, such as focus management, keyboard support and ARIA, with no styles:
- Radix UI: unstyled primitives such as Dialog and Dropdown Menu.
- React Aria: Adobe's hooks and components with thorough accessibility and internationalisation.
- Ark UI: headless components built on state machines.
shadcn/ui is different: its CLI copies component source, built on headless primitives and Tailwind, into your project. You own the code, so customising is easy and updates are your job.
Practice. Build an accessible dropdown menu with a headless library and test it using only the keyboard.
Accessibility in React Core
Accessible React starts with semantic HTML. A <button> gives focus, Enter and Space handling and the right role for free; a <div onClick> gives none of that.
- Label every input with
<label htmlFor>oraria-label; give images usefulalttext, or emptyaltif decorative. - ARIA attributes keep their hyphens in JSX:
aria-expanded,aria-describedby. - Manage focus on route changes, modal open and close, and after deleting an item.
- Use
useIdto link labels and descriptions with IDs that match on server and client.
Add eslint-plugin-jsx-a11y, test with the keyboard and a screen reader, and use role-based test queries, which push you toward accessible markup.
Practice. Audit one page with only the keyboard and fix every element you cannot reach or operate.
Animation Optional
Start with CSS transitions for hover effects and simple entrances, animating transform and opacity, which avoid layout work. Use a library when animation depends on React state, especially for elements leaving the tree:
- Framer Motion, now published as Motion, offers declarative
animateandexitprops, layout animations andAnimatePresencefor unmounting elements. - react spring uses spring physics instead of fixed durations, which suits drag and gestures.
- GSAP is a general animation library for complex timelines and scroll-driven sequences.
<AnimatePresence>
{isOpen && <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} />}
</AnimatePresence>Always honour the prefers-reduced-motion setting.
Practice. Animate a list so new items fade in and deleted items slide out, with motion turned off under reduced motion.
Stage 6 Routing, Data Fetching and Forms
Goal. Build multi-page apps that load, cache, validate and submit data correctly.
Routing with React Router Core
Routing maps URLs to screens without full page reloads. React Router, the react-router package, is the most widely used option.
const router = createBrowserRouter([
{ path: '/', element: <Layout />, children: [
{ index: true, element: <Home /> },
{ path: 'users/:id', element: <UserPage /> },
{ path: '*', element: <NotFound /> },
]},
]);
root.render(<RouterProvider router={router} />);
// inside UserPage: const { id } = useParams();Nested routes render inside the parent's <Outlet />, so shared layouts are natural. <Link> navigates, useNavigate navigates from code, and useSearchParams reads the query string. Routes can also load data with loaders.
TanStack Router is a newer, TypeScript-first alternative: paths, params and search params are fully typed, and search params can be validated with a schema. Learn React Router first.
Practice. Build an app with a shared layout, a /products/:id route, a 404 page and a URL filter.
API Calls Core
Hand-written API calls show what data libraries automate. Track loading and error state, and ignore responses for outdated inputs:
useEffect(() => {
const controller = new AbortController();
setStatus('loading');
fetch(`/api/users/${id}`, { signal: controller.signal })
.then(r => { if (!r.ok) throw new Error(r.statusText); return r.json(); })
.then(data => { setUser(data); setStatus('done'); })
.catch(err => { if (err.name !== 'AbortError') setStatus('error'); });
return () => controller.abort(); // cancel the stale request
}, [id]);Without the abort, a slow response for an old id can overwrite a newer one: a race condition. fetch does not reject on 404 or 500, so check r.ok. Axios is a popular alternative with automatic JSON, errors for failed statuses and interceptors for auth headers. In real apps, prefer a data library or framework loaders.
Practice. Build a user lookup and prove, with an artificially slow API, that stale responses never show.
Server State with TanStack Query and SWR Core
Server data is a cache of something you do not own. TanStack Query and SWR handle caching by key, deduplication, background refetching and retries.
const { data, isPending, error } = useQuery({
queryKey: ['todos', filter],
queryFn: () => fetch(`/api/todos?f=${filter}`).then(r => r.json()),
});
if (isPending) return <Spinner />;
if (error) return <p>Failed to load</p>;
return <TodoList items={data} />;Writes use useMutation, then invalidate related keys, or update the cache optimistically and roll back on error. SWR, named after the stale-while-revalidate strategy, offers a smaller API around one useSWR hook. For GraphQL backends, Apollo Client adds a normalised cache, Relay adds compiler-checked fragments beside each component, and urql is a lighter option; the GraphQL Roadmap covers the API side.
Practice. Replace the fetch effects in a small app with TanStack Query and add a mutation that invalidates the list.
Form Libraries Recommended
Large forms need validation, error messages, touched and dirty tracking, field arrays and submit state, so most teams use a library:
- React Hook Form is the common default. It registers mostly uncontrolled inputs, so typing does not re-render the whole form, and it plugs into schema validators.
- Formik was the earlier standard with controlled inputs. It remains in many codebases but sees little development, so prefer React Hook Form for new work.
- Formisch is a newer, small, schema-first library from the author of Valibot.
const { register, handleSubmit, formState: { errors } } =
useForm({ resolver: zodResolver(schema) });
<form onSubmit={handleSubmit(save)}>
<input {...register('email')} />
{errors.email && <span>{errors.email.message}</span>}
</form>
Practice. Build a checkout form with React Hook Form, including a dynamic list of shipping addresses.
Types & Validation with Zod and Valibot Recommended
TypeScript types vanish at runtime, so they cannot check data from users, URLs or APIs. Schema libraries close the gap: describe the shape once, validate at runtime, and infer the static type from the same schema.
const User = z.object({
id: z.number(),
email: z.string().email(),
role: z.enum(['admin', 'member']),
});
type User = z.infer<typeof User>;
const user = User.parse(await res.json()); // throws if invalidZod is the most common choice and integrates with form libraries and routers. Valibot has a similar model built from small functions, so bundles include only what you use. Validate at every boundary: forms, URLs, API responses and server requests.
Practice. Validate an API response with a schema and show a friendly error when the shape is unexpected.
Stage 7 State Management at Scale
Goal. Decide where each piece of state should live and use a global store only when it pays for itself.
Kinds of State and Where They Live Core
Good state management starts with classifying state, because each kind has a natural home:
| Kind | Example | Home |
|---|---|---|
| Local UI | Dropdown open | useState |
| Shared UI | Theme, sidebar | Context or a small store |
| Server | Products, profile | TanStack Query, SWR, loaders |
| URL | Filters, page, tab | Route and search params |
| Form | Drafts, errors | Form state or library |
Start local and lift only when needed. Many apps that once needed a big store mostly kept server data in it; once a server-state library handles that, little remains. Filters in the URL make views shareable and survive refresh.
Practice. Label each piece of state in one of your apps by kind and move one to a better home.
Redux Toolkit and RTK Query Recommended
Redux keeps state in one store that changes only through dispatched actions handled by reducers. That gives predictable updates and time-travel debugging. Redux Toolkit is the official modern way to write it and removes most of the old boilerplate.
const cartSlice = createSlice({
name: 'cart',
initialState: { items: [] },
reducers: {
added(state, action) { state.items.push(action.payload); }, // Immer makes this safe
},
});
const count = useSelector(s => s.cart.items.length);
const dispatch = useDispatch(); // dispatch(cartSlice.actions.added(item))RTK Query, part of the toolkit, fetches and caches data: you define endpoints, it generates hooks such as useGetPostsQuery, and tags drive invalidation. Redux is common in large codebases, so learn it even if you would choose something lighter.
Practice. Build a cart with a Redux Toolkit slice and load products through an RTK Query endpoint.
Zustand Recommended
Zustand is a small hook-based store. You create a store with one function, need no provider, and use it from any component.
const useCart = create(set => ({
items: [],
add: item => set(s => ({ items: [...s.items, item] })),
}));
function CartCount() {
const count = useCart(s => s.items.length); // selector
return <span>{count}</span>;
}Components subscribe through selectors and re-render only when the selected value changes, which avoids the broad re-renders of a large context. Return primitives or stable references from selectors; a new object each time causes a re-render unless you use the shallow comparison helper.
Practice. Move a cart from context to Zustand and confirm with the profiler that unrelated components stop re-rendering.
Other Models: Jotai and MobX Optional
Jotai stores state in atoms: small independent values read and written with a useState-like hook. Derived atoms compute from other atoms, such as atom(get => get(price) * get(qty)), and each component subscribes only to the atoms it uses, so updates are fine-grained.
MobX is reactive: you mark state observable, wrap components in observer, and mutate stores directly; MobX re-renders only the components that read what changed. It is productive for complex domain models but hides data flow. Learn enough of both to work in a codebase that uses them.
Practice. Build a unit converter where several fields are derived atoms of one base value.
Stage 8 TypeScript and Testing
Goal. Type components precisely and write tests that catch real bugs without breaking on every refactor.
TypeScript with React Core
Most professional React code is TypeScript. It catches wrong props and missing cases before the code runs and makes refactors safer. The language is covered in the TypeScript Roadmap; these are the React-specific parts:
type ButtonProps = React.ComponentProps<'button'> & {
variant?: 'primary' | 'danger';
};
function Button({ variant = 'primary', ...rest }: ButtonProps) {
return <button className={variant} {...rest} />;
}
const [user, setUser] = useState<User | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
function onChange(e: React.ChangeEvent<HTMLInputElement>) {}Use React.ReactNode for anything renderable, ComponentProps to extend native elements, and discriminated unions for components with exclusive modes.
Practice. Type a Select<T> component that takes options: T[], getLabel and onChange(value: T).
Testing Strategy, Vitest and Jest Core
Unit tests cover pure functions, reducers and hooks. Component tests render components and check behaviour through the DOM; most tests belong here. A few end-to-end tests cover critical journeys.
Test behaviour, not implementation: assert on what users see and do, not on internals, so tests survive refactors. Mock at the network boundary and test error and empty states.
import { it, expect } from 'vitest';
it('sums price times quantity', () => {
expect(cartTotal([{ price: 5, qty: 2 }, { price: 1, qty: 3 }])).toBe(13);
});Jest has long been the standard runner. Vitest has a nearly identical API but reuses your Vite config, so TypeScript and JSX need no extra setup. Component tests need a jsdom environment.
Practice. Set up Vitest and test every action of a reducer.
React Testing Library Core
React Testing Library renders components into a test DOM and lets you query it the way a user would: by role, label and text. Pair it with user-event to simulate real typing and clicking.
test('shows an error for an invalid email', async () => {
const user = userEvent.setup();
render(<Signup />);
await user.type(screen.getByLabelText(/email/i), 'nope');
await user.click(screen.getByRole('button', { name: /sign up/i }));
expect(await screen.findByText(/valid email/i)).toBeInTheDocument();
});Prefer getByRole, then labels, then text; use test IDs as a last resort. getBy throws if nothing matches, queryBy returns null for asserting absence, and findBy waits for async content. If a role query cannot find an element, the markup often has an accessibility problem.
Practice. Test a todo component: add, toggle and delete an item, and assert the empty state, all through roles and labels.
Mocking Network Requests Recommended
Mocking fetch in each test ties tests to implementation details. Mock Service Worker (MSW) intercepts requests at the network level instead, in Node tests and in the browser.
const server = setupServer(
http.get('/api/user', () => HttpResponse.json({ name: 'Ana' }))
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
test('shows an error when the server fails', async () => {
server.use(http.get('/api/user', () => new HttpResponse(null, { status: 500 })));
render(<Profile />);
expect(await screen.findByText(/could not load/i)).toBeInTheDocument();
});Components run their real fetching code, so switching to Axios or TanStack Query does not break tests.
Practice. Write handlers for success, empty and error responses and test all three states of a data-loading component.
End-to-End Testing with Playwright and Cypress Recommended
End-to-end tests run the built app in a real browser and check whole journeys, catching broken routing, configuration and integration that unit tests miss.
test('user can sign in', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('a@b.com');
await page.getByLabel('Password').fill('secret');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByText('Welcome back')).toBeVisible();
});Playwright, shown above, drives Chromium, Firefox and WebKit, waits automatically, runs in parallel and records traces. Cypress runs inside the browser with an interactive runner. Keep the suite small, because browser tests are slow and can be flaky.
Practice. Write a Playwright test for your project's main journey and run it in continuous integration.
Stage 9 Performance and Concurrent Rendering
Goal. Find real performance problems by measuring and fix them with the right tool.
Measuring Performance Core
Optimise only what you have measured. The React DevTools Profiler records each commit and shows which components rendered, how long they took and why. Highlighting updates reveals unnecessary renders as you click.
For the whole page, use the browser Performance panel and Core Web Vitals: Largest Contentful Paint for loading, Interaction to Next Paint for responsiveness and Cumulative Layout Shift for stability. Measure production builds; development mode is much slower.
Typical culprits: a large tree re-rendering on each keystroke, slow calculations during render, huge lists, heavy bundles and request waterfalls.
Practice. Profile a slow list filter and record the slowest component before changing any code.
React.memo, useMemo and useCallback Core
These tools skip work by reusing earlier results. React.memo skips a re-render when props are shallowly equal. useMemo caches a computed value until its dependencies change. useCallback caches a function's identity.
const Row = memo(function Row({ item, onSelect }) { /* ... */ });
function Table({ rows, query }) {
const visible = useMemo(() => rows.filter(r => r.name.includes(query)), [rows, query]);
const onSelect = useCallback(id => setSelected(id), []);
return visible.map(r => <Row key={r.id} item={r} onSelect={onSelect} />);
}They work as a set: memo on Row is useless if the parent passes a new function each render. Each adds memory, comparisons and noise, so use them where the profiler shows a gain or to keep effect dependencies stable.
Practice. Memoise a slow row, confirm the gain in the profiler, then remove useCallback and watch it break.
React Compiler Recommended
The React Compiler is a build-time tool that adds memoisation to components and hooks automatically, at a finer level than most people write by hand. With it, much manual useMemo, useCallback and memo code becomes unnecessary.
It relies on the Rules of React: render must be pure, props and state must not be mutated, and hooks must follow their rules. Code that breaks them is skipped, and the hooks lint plugin reports why.
Still learn manual memoisation: existing code uses it, interviewers ask about it, and the compiler cannot fix slow algorithms, heavy bundles or waterfalls.
Practice. Enable the compiler in a test project and fix one component it reports as skipped.
Concurrent Features: useTransition and useDeferredValue Recommended
Concurrent rendering lets React prepare a new UI in the background and interrupt it when something urgent, such as typing, happens. You opt in by marking updates as non-urgent.
const [isPending, startTransition] = useTransition();
function selectTab(next) {
startTransition(() => setTab(next)); // interruptible
}
const deferredQuery = useDeferredValue(query);
return <SlowList query={deferredQuery} />;useTransition wraps an update you control and provides isPending; transitions also keep visible content from being replaced by Suspense fallbacks. useDeferredValue lets a slow part of the UI lag behind a fast-changing value. Neither speeds up rendering itself.
Practice. Build a search over 10,000 items where typing stays smooth, using useDeferredValue and a memoised list.
Bundle Size, Code Splitting and Large Lists Recommended
Every kilobyte of JavaScript must be downloaded, parsed and run, which hurts most on slower phones.
- Split by route with
lazyand dynamicimport(), and load heavy features such as charts and editors on demand. - Inspect the bundle with a visualiser plugin to find large or duplicated dependencies.
- Import only what you use so tree shaking can drop the rest.
Thousands of DOM rows are slow however well you memoise. Virtualisation renders only the visible rows and reuses them while scrolling; TanStack Virtual and react-window do the maths. Pagination or better filtering is often the simpler fix.
Practice. Analyse your bundle, lazy-load the largest dependency, then virtualise a 50,000-row list and compare scroll performance.
Stage 10 Server Rendering, Frameworks and Beyond
Goal. Explain how React runs on the server, use modern React APIs, and choose a framework or platform for a real product.
Rendering Strategies: CSR, SSR and SSG Core
Where and when HTML is produced shapes speed and SEO:
- Client-side rendering (CSR): the server sends an empty shell and JavaScript builds the UI. Simple to host, but first paint waits for the bundle.
- Server-side rendering (SSR): HTML is rendered per request, so content appears sooner and crawlers see it.
- Static site generation (SSG): HTML is built ahead of time and served from a CDN; ideal for content that rarely changes.
After SSR or SSG the browser runs hydration: React attaches handlers and state to the existing HTML. The first client render must match the server HTML, or you get a hydration mismatch; dates, random values and reading window during render are common causes.
Practice. Choose a rendering strategy for a blog, a logged-in dashboard and an online store, and justify each.
SSR Frameworks: Next.js, React Router and Astro Core
SSR frameworks bundle routing, server rendering, data loading and build tooling. The React team recommends one for most new full apps.
- Next.js is the most widely used. Its App Router is built on Server Components, with file-based routing, layouts, streaming and server functions. The Next.js Roadmap covers it in depth.
- React Router in framework mode, the successor to Remix, centres on loaders, actions and forms that work before JavaScript loads.
- Astro is content-first: pages ship as HTML with no JavaScript by default, and only interactive islands, which can be React components, hydrate.
A plain Vite single-page app remains a good fit for internal tools and apps behind a login, where SEO does not matter.
Practice. Build a two-page app in Next.js and in Vite, and compare the initial HTML.
React Server Components Recommended
React Server Components run only on the server. Their code never reaches the browser, they can be async and read databases directly, but they cannot use state, effects or browser APIs.
// Server Component: the default in the Next.js App Router
export default async function ProductDetails({ id }) {
const product = await db.product.find(id);
return <><h1>{product.name}</h1><AddToCart id={id} /></>;
}
// AddToCart.jsx
'use client';
export function AddToCart({ id }) { const [qty, setQty] = useState(1); /* ... */ }'use client' marks where client code begins; props crossing it must be serialisable. Unlike SSR, which renders client components to HTML and then hydrates them, Server Components never hydrate. Keep client components as small leaves.
Practice. Move data fetching from a client component into a Server Component and measure the drop in client JavaScript.
Server APIs and Server Functions Recommended
React's server APIs live in react-dom/server. renderToString returns HTML but cannot stream or wait for data. renderToPipeableStream (Node) and renderToReadableStream (web streams) stream HTML as Suspense boundaries resolve. In the browser, hydrateRoot attaches to server HTML.
Server functions, marked 'use server', let client code call server code like a local function; the framework creates the endpoint. Used for forms and mutations they are called Server Actions.
'use server';
export async function addComment(prev, formData) {
const text = String(formData.get('text') ?? '');
if (!text || text.length > 500) return { error: 'Invalid comment' };
await db.comment.create({ text, userId: await requireUserId() });
return { ok: true };
}Every server function is a public endpoint: check authentication, authorisation and input on every call.
Practice. Write a server function that saves a comment and test that it rejects a logged-out user.
Actions and Modern React Hooks Recommended
React 19 added Actions, built-in support for async updates that removes much hand-written pending and error state:
useActionState(action, initial)runs an action and returns its latest result, a wrapped action andisPending.useFormStatus()lets a submit button know whether its form is submitting.useOptimisticshows the expected result at once and reverts if the action fails.use(promise)oruse(context)reads a resource during render, suspending until a promise resolves.
const [state, formAction, isPending] = useActionState(addComment, null);
return (
<form action={formAction}>
<textarea name="text" />
<button disabled={isPending}>Post</button>
{state?.error && <p role="alert">{state.error}</p>}
</form>
);
Practice. Build a like button with useOptimistic that updates instantly and rolls back when the request fails.
Mobile Applications with React Native Optional
React Native uses the same components, JSX, hooks and state libraries to build native mobile applications for iOS and Android. Instead of DOM elements you render native primitives such as View, Text, Pressable and FlatList, styled with a CSS-like JavaScript subset that uses Flexbox.
function Greeting({ name }) {
return (
<View style={{ padding: 16 }}>
<Text style={{ fontSize: 18 }}>Hello, {name}</Text>
</View>
);
}Expo is the recommended starting point and handles builds and device APIs. Navigation, platform differences and native modules are the main new topics. The React Native Roadmap covers them fully.
Practice. Rebuild one web screen in React Native with Expo and note what changed.
Projects to build
Build these in order. Each one should end up in a public repository with a short README that explains your decisions.
- Task list with filtersBeginner
Build a task list where users can add, edit, complete and delete tasks, filter by status, and keep data after a refresh. Store tasks with a
useLocalStoragecustom hook.Components and props · useState · Lists and keys · Controlled forms · Custom hooks
- Movie or book searchIntermediate
Build a search app on a free public API with a debounced search box, a results page and a detail page per item. Handle loading, empty and error states, keep the query in the URL, and never let stale responses win. Then switch to TanStack Query.
React Router · API calls · Race conditions · URL state · TanStack Query
- Multi-step sign-up formIntermediate
Build a three-step registration flow with validation on each step, a review screen, and a final submit to a mock API. Use React Hook Form with a Zod schema, keep every field keyboard accessible, and test the happy path and each validation error.
Form libraries · Zod · Accessibility · React Testing Library · MSW
- Kanban boardAdvanced
Build a board with columns and cards that users can create, edit and move between columns, including by keyboard. Keep board state in a reducer or Zustand store, save with optimistic updates and rollback, and open card details in a lazy-loaded portal modal. Profile it with 500 cards.
useReducer or Zustand · Optimistic updates · Portals · Profiling and memoisation · Playwright
- Full-stack app with Next.jsAdvanced
Build a small product such as a reading tracker or team expense app with authentication, a database and public pages. Use Server Components for reads, validated and authorised server functions for writes, Suspense streaming for slow sections, and error boundaries per route. Deploy it and measure Core Web Vitals.
Server Components · Server functions · SSR and streaming · TypeScript · Deployment
Interview questions
Try to answer each question out loud before you open the answer.
What is the difference between props and state?Junior
Props are inputs from the parent; the child treats them as read-only, like function arguments. State is data the component owns and changes with its setter, like private memory. Changing either triggers a re-render, and a parent's state often becomes its children's props. I keep state minimal: anything derivable from props or other state is computed during render, because duplicated state drifts out of sync.
Why does React need keys in lists, and why is the array index a poor key?Junior
Keys let React match items between renders, so it keeps, moves or removes the right component with its state. With index keys, identity follows position: after an insert, delete or sort, the item now at index 0 inherits the old item's state and DOM, which shows up as wrong input values or checked boxes. A stable ID from the data fixes it. Index keys are fine only for static lists.
Why does a state update not appear immediately after calling the setter?Junior
The setter does not change the variable in the current render; it schedules a new render. Within a render, state is a snapshot, so logging it right after setCount(count + 1) shows the old value. React also batches updates from one event. When the next value depends on the previous one, I use the updater form setCount(c => c + 1). If I need the new value immediately, I compute it into a local variable first.
What is the difference between controlled and uncontrolled components?Junior
A controlled input gets value from state and updates it in onChange, so React is the source of truth; that makes live validation and dependent fields easy, at the cost of a render per keystroke. An uncontrolled input keeps its value in the DOM: you set defaultValue and read it on submit with FormData or a ref, which is less code and fewer renders. React Hook Form builds on uncontrolled inputs for that reason.
Explain the useEffect dependency array and cleanup function.Junior
An effect synchronises the component with an external system after render. With no array it runs after every render, with [] once after mount, and with [a, b] whenever a or b change. The returned function is the cleanup: React runs it before the next run and on unmount, and it is where I unsubscribe, clear timers or abort requests. The array must list every reactive value the effect reads, or it will use stale values.
Why does my effect run twice in development?Mid
In development, StrictMode mounts each component, unmounts it and mounts it again to expose effects without proper cleanup. Production does not do this. The right fix is not a ref guard or removing StrictMode, but a cleanup that makes mount, unmount, mount behave like one mount: unsubscribe, clear the interval or abort the fetch.
How does reconciliation work, and what is the virtual DOM?Mid
Components return plain objects describing the UI, often called the virtual DOM. On each update React builds a new tree and diffs it against the previous one using two shortcuts: different element types produce new subtrees, and list children are matched by key. If type and position stay the same, React keeps the instance and its state and updates only changed attributes. The commit phase then applies the minimal DOM changes.
What causes a component to re-render, and how do you avoid unnecessary re-renders?Mid
A component re-renders when its state changes, its parent re-renders, or a context it reads changes. I measure with the Profiler first, then fix structure: move state down to where it is used, pass expensive subtrees as children, and split contexts. If that is not enough, I use React.memo with props kept stable by useCallback and useMemo, or rely on the React Compiler to add memoisation.
When would you use useMemo, useCallback and React.memo?Mid
useMemo caches an expensive computed value, useCallback caches a function's identity, and React.memo skips a child's render when its props are shallowly equal. They are used together, because memo only helps if the parent passes stable props. They also keep effect dependencies stable. I do not add them by default: they cost memory and readability, so I add them where profiling shows a gain.
What is a stale closure in React, and how do you fix it?Mid
Each render creates functions that capture that render's props and state. A callback from an earlier render, such as an interval set up in an effect with [], keeps reading old values. Fixes: use the updater form of the setter so the current value is not needed, add the value to the dependencies so the effect re-subscribes, or keep the latest value in a ref for long-lived callbacks.
Context or a state management library: how do you decide?Mid
Context solves prop drilling; it is not a store. It suits values that change rarely, such as theme, locale or the current user. Every consumer re-renders on change and there are no selectors, so busy shared state in context causes wide re-renders. For frequently updated shared client state I use a store such as Zustand or Redux Toolkit, with selectors. Server data goes into TanStack Query or SWR, which removes most of the need for a global store.
What are error boundaries, and what do they not catch?Mid
Error boundaries catch errors thrown while rendering their children, log them and show a fallback instead of a blank app. They are class components using getDerivedStateFromError and componentDidCatch, or the react-error-boundary package. They do not catch errors in event handlers, async code outside rendering, server rendering, or the boundary itself. I place one per route and per widget.
How would you fetch data in a React component and avoid race conditions?Mid
In a real app I use TanStack Query or the framework's loaders, which handle caching, deduplication, retries and cancellation. By hand, I fetch in an effect keyed on the inputs, track loading and error state, check response.ok, and return a cleanup that aborts the request with an AbortController. Without it, a slow response for an old input can overwrite the newer result.
Explain server-side rendering, hydration and hydration mismatches.Senior
With SSR the server renders components to HTML, so content shows before JavaScript loads and crawlers can read it. Hydration then renders the same tree in the browser and attaches handlers and state to the existing DOM. If the first client render differs from the server HTML, React reports a mismatch and may re-render that part. Common causes are dates, random IDs, locale formatting and reading window during render; fixes include useId and moving client-only values into an effect.
What are React Server Components, and how do they differ from SSR?Senior
Server Components run only on the server and ship no JavaScript. They can be async and read data directly, but cannot use state, effects or event handlers. SSR is separate: it renders client components to HTML for the first load, and those components then hydrate and run in the browser. Frameworks combine both: the server tree renders, and components marked 'use client' are rendered to HTML and hydrated. Props crossing that boundary must be serialisable.
What problem do useTransition and useDeferredValue solve?Senior
They keep the UI responsive when an update triggers expensive rendering. Concurrent React can render low-priority work in the background and interrupt it for urgent input like typing. useTransition marks an update I control as non-urgent and gives isPending; it also stops visible content being replaced by Suspense fallbacks. useDeferredValue lets a slow child lag behind a value I receive. Neither makes rendering faster, so they pair with memoisation and virtualisation.
How would you structure state in a large React application?Senior
I classify it first. Server data goes into TanStack Query, RTK Query or framework loaders. Shareable view state such as filters and pagination goes in the URL. Form state stays in the form library and local UI state stays in its component. What remains, genuinely global client state, goes into context if it changes rarely or a store such as Zustand or Redux Toolkit with selectors. I never duplicate server data in stores.
Common mistakes
- Copying props into state or syncing values with an effect; compute derived values during render instead.
- Mutating state with
pushor by assigning to a property and wondering why nothing updates; create a new array or object every time. - Using the array index or
Math.random()as a list key; use a stable ID from the data. - Leaving effects without cleanup, causing leaked subscriptions, duplicate listeners and race conditions; return a cleanup function and abort stale requests.
- Silencing the hooks dependency lint rule; fix the code by moving functions into the effect or using the updater form instead.
- Putting every piece of shared state, including server data, into one global store or one large context; separate server, URL, form and local state first.
- Building clickable
divelements and unlabelled inputs; use semantic elements, labels and keyboard testing from the start. - Testing implementation details such as state values or component internals; test what the user sees and does with role-based queries.
Ready-for-interview checklist
- I can build a multi-component app from a mock-up, choosing sensible component boundaries and props.
- I can explain the render and commit phases and predict which components re-render after a state change.
- I can explain why keys matter and show the bug that index keys cause.
- I can write effects with correct dependencies and cleanup, and I know when an effect is not needed.
- I can build controlled and uncontrolled forms and validate them with a schema.
- I can write a custom hook and explain the rules of hooks and why they exist.
- I can decide where a piece of state should live and justify context versus a store.
- I can fetch and mutate data with TanStack Query and handle loading, error and race conditions.
- I can type components, events, refs and generic components in TypeScript.
- I can test components with React Testing Library and MSW and write an end-to-end test.
- I can use the Profiler to find a slow component and fix it with memoisation or transitions.
- I can explain SSR, hydration, Server Components and when to choose a framework.
Related roadmaps
- JavaScript RoadmapLanguage core, async, the event loop, modules and the DOM.
- TypeScript RoadmapTypes, generics, narrowing, utility types and project setup.
- Next.js RoadmapApp Router, server components, data fetching, caching and deployment.
- React Native RoadmapComponents, navigation, native modules, performance and release.
- CSS RoadmapCascade, layout with flexbox and grid, responsive design, animation.
- GraphQL RoadmapSchemas, resolvers, N+1, caching, federation and security.
FAQ
How long does it take to learn React?
With solid JavaScript, most people build simple React apps after two to four weeks of regular practice. Reaching the level expected in a junior or mid-level interview, including routing, data fetching, testing and performance, usually takes three to four months at around eight hours a week. Building matters more than reading.
Should I learn JavaScript before React?
Yes. React is mostly plain JavaScript, and many beginner React problems are really JavaScript problems such as reference equality or closures. You do not need to master everything, but be comfortable with the topics in the JavaScript Roadmap first, and add TypeScript later.
Should I learn React or Next.js first?
Learn React first. Next.js adds routing, server rendering and its own conventions, and it is much easier to tell which behaviour comes from React and which from the framework after building a few Vite apps. Once you finish stage six here, the Next.js Roadmap is a natural next step.
Is React still worth learning?
Yes. React remains one of the most widely used front-end libraries, with a large job market, a mature ecosystem and active development. Its ideas, such as components, one-way data flow and declarative rendering, also transfer to Vue, Svelte and Angular.
Do I still need to learn class components and Redux?
Write new code with functions and hooks, but learn to read class components: many codebases still contain them, and error boundaries are still classes. Learn modern Redux Toolkit once React's built-in state tools feel natural. Many jobs use it, though many new apps get by with TanStack Query plus context or Zustand.