Moonlit Torii

Front-End Interview Notes

Front-end interview notes covering Vue 3, advanced JavaScript, React, and common front-end scenarios.

Part 1: Vue 3

Vue 3 Reactivity Fundamentals

Vue 3 reactivity flow: track dependencies on read, trigger effects on write, and batch DOM updates

Vue 3 uses Proxy traps for object operations: track collects dependencies on reads, trigger notifies effects on writes, and the scheduler batches rendering work.

APIBest forWatch out for
refPrimitives or objects; the general defaultUse .value in scripts; templates unwrap it automatically
reactiveObject state with a stable shapeReplacing the object or destructuring primitive properties breaks the reactive connection
toRef / toRefsPreserving reactivity while destructuringThe result stays linked to the source property; it is not a snapshot
shallowRef / markRawLarge immutable data or third-party instancesMake update boundaries explicit; do not use them by default

Interview focus: the proxy and raw object have different identities. Mutate the proxy, and explain the boundaries around destructuring, object replacement, and large deeply reactive structures.

computed, watch, and watchEffect

Responsibilities of computed, watch, and watchEffect

APIMain purposeKey behavior
computedDerive a value from existing stateLazy and cached; keep the getter pure
watchObserve explicit sources preciselyProvides new and old values; suited to requests, logging, and other effects
watchEffectAutomatically track dependencies read during synchronous executionRuns immediately by default; concise, but dependencies are less explicit

Async watchers should cancel or invalidate stale work to avoid races. watchEffect only tracks dependencies accessed synchronously before the first await. Avoid deep watching large object trees.

nextTick and Batched DOM Updates

Vue 3 execution order from state writes to batched updates and nextTick

  • Reactive state changes synchronously, while DOM updates are queued, deduplicated, and batched.
  • await nextTick() means Vue has finished the current DOM patch; it does not guarantee browser paint or wait for network and image loading.
  • Use it only when you must read or manipulate the latest DOM after changing state. Regular data flow should not depend on it.

Composition API and Composables

Multiple components reuse stateful logic through a composable

  • <script setup> is the recommended single-file component syntax for the Composition API, and top-level bindings are available directly in templates.
  • A composable is a function for reusable stateful logic, usually prefixed with use; keep inputs, outputs, and side effects explicit.
  • Return refs, readonly state, and action functions so destructuring preserves reactivity. Put DOM effects in lifecycle hooks and clean them up.
  • Reuse UI with components, stateful logic with composables, and stateless calculations with plain utility functions.

Compared with mixins, composables make data origins clearer, avoid most naming collisions, and improve type inference and composition.

This is Part 1 of the front-end interview notes. It distills the existing Vue 3 notes into common conclusions, mechanisms, and pitfalls. A strong answer starts with the conclusion, then adds the mechanism and applicable scenario.

Vue 3 lifecycle

A Vue component goes through creation, mounting, updating, and unmounting. Lifecycle hooks let us run side effects at those stages, such as fetching data, reading the DOM, registering listeners, and releasing resources.

Common hook equivalents

StageOptions APIComposition APITypical use
Before creationbeforeCreatesetup() itselfEarly initialization; rarely needed separately
Createdcreatedsetup() itselfEstablish non-DOM state
Before mountbeforeMountonBeforeMountFinal work before the first render
MountedmountedonMountedAccess the DOM or initialize third-party libraries
Before updatebeforeUpdateonBeforeUpdateRead the old DOM state before an update
UpdatedupdatedonUpdatedWork that depends on the latest DOM
Before unmountbeforeUnmountonBeforeUnmountLast work before cleanup
UnmountedunmountedonUnmountedRemove listeners, timers, and subscriptions
Cache activatedactivatedonActivatedA KeepAlive component becomes active
Cache deactivateddeactivatedonDeactivatedA KeepAlive component enters the cache
Descendant errorerrorCapturedonErrorCapturedLocal error boundaries and reporting

There are no onBeforeCreate or onCreated hooks. In the Composition API, setup() already covers the main use cases of those two Options API hooks.

Parent-child mounting generally runs as: parent beforeMount → child mounting → parent mounted. Update order follows the dependencies that changed; during unmounting, the parent enters first and completes after its children.

Common pitfalls

  • Register hooks synchronously from setup().
  • onMounted does not guarantee that images, async components, or requests are complete.
  • Avoid unconditional state mutations in onUpdated to prevent update loops.
  • Clear timers, events, observers, and subscriptions on unmount.
  • SSR does not run onMounted, onUpdated, or onUnmounted.

Vue 2 vs Vue 3

Vue 3 changed more than reactivity: application instances, logic reuse, compiler optimizations, TypeScript support, and tooling also evolved. Templates, components, and one-way data flow remain familiar.

AreaVue 2Vue 3
Reactive objectsPrimarily Object.definePropertyreactive primarily uses Proxy; ref tracks .value through accessors
Adding or deleting propertiesOften needs Vue.set and Vue.deleteProxy can track additions and deletions
API organizationPrimarily Options APIOptions API remains available; Composition API is added
Application entrynew Vue() and global APIscreateApp() returns an isolated application instance
Root nodesOne root nodeComponents support fragments and multiple root nodes
Logic reuseMixins can obscure sources and cause name collisionsComposables group capabilities explicitly with type inference
TypeScriptAdded later, with a limited type experienceThe core is written in TypeScript and SFC tooling is stronger
RenderingMostly runtime diffingCompiler-provided patch flags, static caching, and block information
State managementVuex is the common solutionPinia is recommended for new projects; Vuex 4 remains viable for migration
Build toolingVue CLI and webpack are commonVite is the default recommendation for new projects

Reactivity differences

Vue 2 recursively walks an object and converts existing properties to getters and setters. This creates special constraints around new properties and array indexes. Vue 3 proxies objects and can intercept more operations. That does not make every variable reactive, however: destructuring a reactive object can still disconnect a value from reactivity.

Common migration changes

  • beforeDestroy and destroyed became beforeUnmount and unmounted.
  • Declare events with emits or defineEmits; component v-model uses modelValue plus update:modelValue.
  • $on, $off, $once, filters, and $children were removed; $listeners was merged into $attrs.
  • v-if has higher priority than v-for on the same element, though mixing them is still discouraged.

Avoid the vague interview answer that “Vue 3 is simply faster.” A more precise explanation is that Vue 3 uses compile-time hints to reduce runtime traversal and comparison while also improving reactivity, logic reuse, and typing.

Passing data in Vue 3

Vue 3 still follows “props down, events up.” Other mechanisms address two-way binding, deep dependencies, slots, imperative access, and shared state.

Relationship or scenarioPreferred mechanismNotes
Parent to childprops / definePropsThe child reads data owned by the parent
Child to parentemit / defineEmitsSend payloads through clearly named events
Controlled two-way bindingComponent v-model / defineModelA prop combined with an update:* event
Fallthrough attributes and listeners$attrs / useAttrsUseful for wrappers; multi-root components need an explicit target
Parent-provided template contentSlots / defineSlotsScoped slots expose child data to parent-authored templates
Deep component treeprovide / injectSuitable for themes, form context, and component-library internals
Imperative parent accessTemplate refs / defineExposeReserve for focus, scrolling, dialogs, and similar capabilities
Shared application statePiniaSuitable for users, permissions, carts, and other cross-page state

props and emit

Props are shallowly readonly. A child should not mutate a prop or change an object's nested fields merely to bypass clear ownership. Emit an event and let the parent update its own state.

Component v-model

Starting with Vue 3.4, defineModel() is the recommended way to implement component v-model. It returns a ref; underneath, the contract is still a prop and an update:* event.

vue
<script setup lang="ts">
const model = defineModel<string>({ required: true })
</script>

<template>
  <input v-model="model" />
</template>

The parent can use <SearchInput v-model="keyword" />. Before Vue 3.4, declare a modelValue prop and emit update:modelValue explicitly.

provide and inject

For deep dependencies, prefer a Symbol and InjectionKey to prevent collisions and share types. Expose mutation functions from the provider so ownership stays clear.

Do not reach for Pinia solely because a dependency crosses several levels. Context limited to one component subtree usually belongs in provide/inject; business state independent of the component tree and shared across pages is a better fit for Pinia.

Vue 3 diffing

Diffing does not seek the theoretical minimum edit distance. It synchronizes the new VNode tree with the real DOM at a predictable cost by combining compiler hints with runtime diffing.

From a template to a page update

  1. Compile: the template becomes a render function that returns a VNode tree.
  2. Mount: the renderer runs that function and creates real DOM while a reactive effect records the dependencies read during rendering.
  3. Patch: after a dependency changes, Vue creates a new VNode tree, compares it with the previous tree, and applies the necessary DOM changes.

Vue 3 compiler optimizations

  • Static caching: static VNodes are reused after the first render and skipped during updates.
  • Patch flags: the compiler records whether only text, class, style, or specific props can change.
  • Block tree / tree flattening: a block collects only dynamic descendants, avoiding a walk through the entire static tree.
  • Stable fragments: when child order is known to be stable, runtime child-order reconciliation can be skipped.

How keyed children are compared

For a keyed list, the core process can be summarized as follows:

  1. Synchronize nodes with the same type and key from the start.
  2. Synchronize matching nodes from the end.
  3. If the old list ends first, mount the remaining new nodes; if the new list ends first, unmount the remaining old nodes.
  4. Build a key → new index map for the unordered middle section.
  5. Walk the old middle section. Unmount missing nodes, patch reusable nodes, and record the old-to-new index relationship.
  6. Compute the longest increasing subsequence for nodes that may move. Nodes in the sequence stay in place; the others are inserted or moved in reverse order, reducing DOM movement.

The longest increasing subsequence optimizes movement only; reuse is decided first by VNode type and key.

Rules for keys

  • A key should be unique among siblings, stable, and represent a business entity.
  • Do not use an array index when the list can be inserted, deleted, or reordered.
  • A random key changes every render and repeatedly destroys and recreates nodes.
  • An unkeyed list tends to patch same-type nodes in place, which may preserve unexpected input state.
  • More keys are not automatically better. A key is an identity hint and can intentionally force component replacement or lifecycle execution.

Vue Router

Vue Router navigation from triggering a route change and matching a route through guards, loading, and rendering

Vue Router is Vue's official client-side router. It changes page components when the URL changes without reloading the whole document, while preserving browser history and shareable links.

Common objects

APIPurposeTypical use
useRoute()Information about the current pageRead params, query, meta, and the current path
useRouter()Navigation controllerCall push(), replace(), or back()
<RouterLink>Declarative navigation linkNavigate inside the app instead of using a plain <a>
<RouterView>Outlet for page componentsDisplays the component matched by the current URL

params form part of the path, such as 10 in /users/10; query contains filters after ?, such as /users?page=2. Moving from /users/1 to /users/2 may reuse the same component, so watch the parameter or use onBeforeRouteUpdate() to reload data.

History modes

ModeURLImportant detail
createWebHistory()/users/10Recommended; the server must fall back unknown paths to index.html or refreshes return 404
createWebHashHistory()/#/users/10Needs no server fallback, but includes # and is weaker for SEO
createMemoryHistory()Does not control the browser URLCommon in SSR and tests

Guards and lazy loading

  • router.beforeEach() performs global checks such as authentication and permissions. Return false to cancel or a route location to redirect.
  • beforeEnter protects one route.
  • onBeforeRouteLeave() can warn about unsaved edits.
  • Define a route component with () => import(...) so its code is downloaded only when the user visits it.
ts
const routes = [
  {
    path: "/users/:id",
    name: "user",
    component: () => import("./views/UserPage.vue"),
    meta: { requiresAuth: true },
  },
]

router.beforeEach((to) => {
  if (to.meta.requiresAuth && !isLoggedIn) {
    return { name: "login" }
  }
})

Remember: route describes the current page, while router controls navigation. History mode needs a server fallback, permissions belong in guards, and page components should be lazy-loaded by route.

State management with Pinia

Pinia is the officially recommended state-management solution for Vue. Stores are defined with defineStore(), there is no Vuex mutation layer, and the library provides strong TypeScript inference, Devtools integration, plugins, and SSR support.

The three core concepts

  • state: mutable data, comparable to component data.
  • getters: values derived from state, comparable to computed.
  • actions: synchronous or asynchronous business operations, comparable to methods.

Pinia supports Option Stores and Setup Stores: the former are structured, while the latter can directly use refs, computed values, watchers, and composables.

ts
// stores/counter.ts
import { computed, ref } from "vue"
import { defineStore } from "pinia"

export const useCounterStore = defineStore("counter", () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)

  function increment() {
    count.value += 1
  }

  async function loadCount() {
    const response = await fetch("/api/count")
    const data: { count: number } = await response.json()
    count.value = data.count
  }

  function $reset() {
    count.value = 0
  }

  return { count, doubleCount, increment, loadCount, $reset }
})

A Setup Store must return every state property managed by Pinia. Hiding state or making it readonly can break SSR, Devtools, and plugin behavior.

A store is reactive; directly destructuring state or getters breaks reactivity, so use storeToRefs(). Bound actions can be destructured directly.

Mutations and common pitfalls

  • State can be changed directly or grouped with $patch().
  • Option Stores provide $reset(); Setup Stores implement it themselves.
  • Actions can be asynchronous and do not need a separate Vuex-style mutation step.
  • Do not move every piece of temporary component state into Pinia. Local state belongs in a component or composable.
  • Persistence is not a Pinia core feature; storage requires attention to sensitive data, migrations, serialization, and SSR.
  • Stores can call one another, but avoid circular dependencies during definition. Cross-store reads usually belong inside an action or getter at execution time.

A concise interview answer is: Pinia centralizes business state shared across components and pages; state holds data, getters derive data, and actions implement business operations; use storeToRefs() when destructuring reactive store data in a component.

Vuex vs Pinia

Vuex and Pinia architecture: Vuex includes a mutation layer, while Pinia consists of state, getters, and actions

Pinia is the next generation of Vue state management. Instead of continuing with Vuex 5, the Vue team made Pinia the default recommendation because it already implemented most of the intended design.

AreaVuex 3 / 4Pinia
Core structurestate, getters, mutations, actionsstate, getters, actions
State updatesAn action usually commits a mutationDirect updates, actions, or $patch()
ModulesModules and namespaces under one StoreMultiple flat Stores, isolated by Store ID
TypeScriptOften needs type wrappers or string keysDesigned for direct inference and autocomplete
Dynamic behaviorDynamic modules require registrationStores are created on demand
Composition APISupported, but not the original design centerNative Option Store and Setup Store APIs

Why Pinia is preferred for new projects

  • Less ceremony: no mutation layer or nested namespaces, so update paths are shorter.
  • Stronger typing: import Stores directly without extensive string keys or custom wrappers.
  • Natural composition: Stores can call other Stores and reuse composables.
  • Complete tooling: Devtools, SSR, plugins, testing utilities, and HMR remain supported.
  • Simpler splitting: independent Stores are easier to maintain and load on demand than deeply nested modules.

“Better” refers mainly to API, typing, and maintainability in new projects. Stable Vuex 3/4 applications do not need an immediate rewrite: they can migrate module by module, and Vuex can coexist with Pinia during the transition.

Part 2: Advanced JavaScript

Start with the conclusion, then explain the runtime mechanism and its boundaries. The goal is not API recall, but explaining why code behaves as it does.

Scope, Execution Context, and Closures

The relationship between JavaScript execution contexts, lexical environments, and closures

  • Scope is determined by where code is defined. Identifier lookup walks outward through lexical environments.
  • Every function call creates an execution context containing parameters, local bindings, this, and an outer reference.
  • var is hoisted and initialized to undefined; let and const stay in the temporal dead zone before declaration.
  • A closure is a function together with the outer bindings it can access. Those bindings remain alive while the closure is reachable.

this and Function Calls

this binding rules for regular and arrow functions in JavaScript

Call formthis in a regular function
fn()undefined in strict mode; usually the global object in a non-strict script
obj.fn()The receiver before the dot, obj
call / apply / bindThe explicitly supplied value
new Fn()The newly created instance

For regular functions, inspect the call site. A useful priority is new > explicit > implicit > default. Arrow functions have no own this, capture it lexically, and cannot be constructors.

Prototype Chain, new, and class

JavaScript prototype lookup and the steps performed by new

  • Property lookup starts on the object and follows [[Prototype]] until null.
  • An instance delegates to the constructor's prototype; instanceof essentially checks this chain.
  • new creates an object, links its prototype, calls the constructor with that object as this, and then determines the return value.
  • class is clearer syntax built on the prototype mechanism; shared methods still live on the prototype.

Promise and async/await

Promise states, chain propagation, and await

  • A Promise moves once from pending to fulfilled or rejected; settlement is irreversible.
  • then and catch return a new Promise: a value fulfills it, a thrown error rejects it, and a returned Promise is adopted. finally normally preserves the prior result.
  • An async function always returns a Promise. await pauses only that function, and its continuation runs as a microtask.

Iterator → Generator → async/await

A conceptual path from iterators and generators through async iterators to async/await

This is a learning path for suspension and resumption, not a specification claim that async/await must be implemented with generators.

MechanismCore contractSuspension and resumption
Iteratornext() synchronously returns { value, done }The consumer pulls the next value; an iterator does not suspend an ordinary function
Generatorfunction* returns an iterable iteratoryield suspends; next(value) passes a value and resumes, while .throw(error) injects an error
Async iteratornext() returns Promise<IteratorResult>async function* can use both await and yield, and for await...of consumes it
async/awaitasync returns a Promise; await accepts any valueThe value follows Promise resolution, continuation resumes as a microtask, and rejection throws at await

It is useful to model async/await as “generator-like suspension plus a Promise runner,” but the returned objects and language semantics differ. Even an already-settled Promise does not continue after await on the current synchronous stack.

CombinatorResult
Promise.allFulfills when all fulfill; rejects early but does not cancel the other work
Promise.allSettledWaits for every result and preserves each outcome
Promise.raceAdopts the first settlement, whether fulfilled or rejected
Promise.anyAdopts the first fulfillment; rejects only if all reject

For concurrency, start the work before awaiting it together. When requests can become stale, use AbortController or a result version to prevent races.

The JavaScript Event Loop

Each browser turn runs one macrotask, drains all microtasks, may render, and then starts the next turn

Start with two kinds of work:

  • A macrotask is one complete job, such as running a script, handling one click, or running one timer callback. Each turn selects only one macrotask.
  • A microtask is follow-up work that must run immediately after the current macrotask. It has priority over the next macrotask, and the whole microtask queue must be drained.

Execution process

  1. Select and run one macrotask. On initial page load, the whole synchronous script is the first macrotask.
  2. New macrotasks and microtasks created during execution are placed in their matching queues.
  3. When the current macrotask finishes, drain all microtasks. Microtasks created by other microtasks are also processed.
  4. Once the microtask queue is empty, the browser may update the page.
  5. Select the next macrotask and repeat.

The exact order is therefore: one macrotask → all microtasks → possible rendering → next macrotask. The browser does not run every macrotask first and postpone all microtasks until later.

Common macrotasks and microtasks

TypeCommon sourceMeaning
MacrotaskThe initial whole scriptSynchronous code that starts when the page loads
MacrotasksetTimeout and setInterval callbacksExpiry only queues the callback; it does not run immediately
MacrotaskDOM events such as click and inputUser events enter a task queue
MacrotaskpostMessage and MessageChannel callbacksMessages wait in a task queue
MicrotaskPromise.then/catch/finallyQueued after the Promise settles
MicrotaskCode after awaitPromise continuation work
MicrotaskqueueMicrotaskDirectly adds a microtask
MicrotaskMutationObserver callbacksReports DOM changes as microtasks

The browser handles the network part of fetch, so the request itself should not simply be labeled a macrotask or microtask. Code in .then() or after await is a microtask. requestAnimationFrame belongs to the rendering stage and should not be forced into either queue.

Execution-order example

js
console.log(1)

setTimeout(() => console.log(5), 0)

Promise.resolve().then(() => console.log(3))
queueMicrotask(() => console.log(4))

console.log(2)

The output is 1 → 2 → 3 → 4 → 5. The whole script is the first macrotask and prints 1, 2; the two microtasks then print 3, 4; finally, the timer macrotask prints 5.

Remember: one macrotask at a time, but drain every microtask each time. If microtasks keep creating more microtasks, rendering and the next macrotask continue to wait. Node.js has different phases and queues; this section describes the browser event loop.

Deep Copy vs Shallow Copy

A shallow copy shares nested objects, while a deep copy has independent outer and nested objects

  • A shallow copy copies only the outer layer. The two outer objects differ, but nested objects are still shared, so changing nested data affects both.
  • A deep copy also copies nested objects. Changing the copy no longer changes the original.

Shallow copy

Spread syntax and Object.assign() copy only the first layer.

js
const original = {
  name: "Jack",
  address: { city: "Shanghai" },
}

const shallowCopy = { ...original }

shallowCopy.name = "Tom"
shallowCopy.address.city = "Beijing"

console.log(original.name) // "Jack": outer values are independent
console.log(original.address.city) // "Beijing": nested object is shared

Deep copy

Modern browsers provide structuredClone(), which also copies supported nested data.

js
const original = {
  name: "Jack",
  address: { city: "Shanghai" },
}

const deepCopy = structuredClone(original)

deepCopy.address.city = "Beijing"

console.log(original.address.city) // "Shanghai"
console.log(deepCopy.address.city) // "Beijing"

Writing const copy = original only makes two variables point to the same object; it is not a copy. structuredClone() supports objects, arrays, Map, Set, dates, and cycles, but not functions or DOM nodes. JSON.parse(JSON.stringify(value)) loses some data types and is not a general-purpose deep-copy solution.

Remember: a shallow copy replaces the outer shell; a deep copy also duplicates what is inside.

Browser Rendering and Performance

Browser rendering from DOM and CSSOM through layout, paint, and compositing

You can think of browser rendering as: read HTML for structure → read CSS for styles → calculate size and position → draw pixels → combine layers.

  • Layout (reflow) recalculates how large elements are and where they belong.
  • Paint (repaint) redraws pixels such as colors, borders, and shadows.
  • Compositing places already-painted layers in the right position and is usually cheaper.
Common situationPossible problemBetter approach
Animating width, height, top, or leftLayout is recalculated repeatedlyPrefer transform and opacity for animation
Reading dimensions and changing styles in the same loopThe browser repeatedly forces layoutRead everything first, then write everything
Updating the screen on every scroll eventToo many calls can drop framesThrottle the handler and update inside requestAnimationFrame
Rendering thousands of rows at onceDOM, layout, and paint all become expensiveUse pagination or a virtual list
Loading many large imagesDownloading, decoding, and painting take timeCompress images, set dimensions, and lazy-load them

Script loading also affects the first screen. Normal application scripts usually use defer: they keep document order and run after HTML parsing. Independent scripts such as analytics may use async: they run as soon as they are ready and do not preserve order.

Remember: avoid repeated calculations and avoid drawing invisible content. Move layers for animation instead of repeatedly changing layout. transform and opacity often make compositing possible, but they do not guarantee zero painting cost in every case.

Events, Debounce, and Throttle

DOM event propagation and the difference between debounce and throttle

When an element is clicked, the event travels from the outside to the target and then bubbles back out. We can use bubbling to place one listener on a parent and handle all of its buttons. This is event delegation, and it is useful for lists, tables, and elements added later.

Common situationChooseWhy
Search input, form validation, relayout after resizing stopsDebounceWait until the user pauses, then run only the last call
Scrolling, dragging, mouse movement, scroll progressThrottleRun at a fixed interval while the action continues
Many delete or edit buttons in a listEvent delegationListen on the parent instead of binding every button

Debounce

Think of it as “wait until the user is finished.” Every trigger restarts the timer, which makes it suitable for search input.

js
function debounce(fn, delay = 300) {
  let timer

  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => fn(...args), delay)
  }
}

const search = debounce((keyword) => {
  console.log("Search:", keyword)
}, 300)

Throttle

Think of it as “run at most once per time window while the action continues.” This simple version runs immediately on the first trigger.

js
function throttle(fn, interval = 200) {
  let canRun = true

  return (...args) => {
    if (!canRun) return

    canRun = false
    setTimeout(() => {
      canRun = true
    }, interval)

    fn(...args)
  }
}

const updateScrollProgress = throttle(() => {
  console.log("Update scroll progress")
}, 200)

Remember: use debounce when only the final action matters; use throttle when updates are still needed during continuous activity. Search should also cancel stale requests, and submit buttons need a request lock rather than relying only on debounce or throttle.

Part 3: React

This part starts with what happens after state changes and keeps only the React topics most often discussed in interviews: rendering, Hooks, data flow, performance, and routing. Explain how data moves first, then name the APIs.

React Rendering, Fiber, and Diffing

React moves from a state update through scheduling, Render, Commit, and browser paint

Remember an update as: trigger → schedule → calculate during Render → change the DOM during Commit → browser paint.

PhaseWhat happensMay touch the DOM?
Trigger and schedulingA state setter requests an update; React schedules work by priorityNo
RenderReact calls components, builds the next element tree, and reconciles differencesNo; rendering must stay pure
CommitReact applies DOM changes, updates refs, and runs layout-related effectsYes; this phase cannot be interrupted
After browser paintReact normally runs useEffectIt may sync external systems; keep it light

What Fiber solves

Fiber breaks the component tree into schedulable units of work. React may pause, resume, or discard uncommitted Render work so urgent updates such as typing can go first. Commit must still finish as one unit, so users never see a half-updated page.

Fiber's main value is scheduling, not simply “making Diff faster.” Render may run more than once, so a component body must not send requests, mutate the DOM, or change external variables.

Diffing and keys

  • When element types differ, React normally removes the old subtree and mounts a new one. Matching types continue with props and children.
  • Type and key together identify a component. A stable identity under the same parent lets React preserve state and DOM correctly.
  • Do not use an array index when a list can be inserted into, deleted from, or reordered. A random key remounts the item on every render.
  • A key only needs to be unique among siblings and is not passed to the component as a normal prop.

Remember: Render calculates, Commit changes; type and key decide whether an identity can be reused.

Core React Hooks

Responsibilities of useState, useEffect, useRef, memoization, and custom Hooks in a React component

Call Hooks only at the top level of a function component or custom Hook—not inside conditions, loops, or ordinary functions. React relies on a stable call order to associate each Hook with its state.

HookMain useCommon pitfall
useStateData that affects renderingEach render sees a snapshot; use functional updates for old values
useEffectSynchronizing requests, subscriptions, and timersDeclare every dependency and clean up before reruns and unmounts
useRefA DOM node or mutable value outside renderingChanging .current does not trigger a render
useMemoCaching an expensive calculationIt is an optimization, not a correctness guarantee
useCallbackCaching a function identityUsually useful with a memoized child or as a Hook dependency
Custom HookReusing stateful logicStart with use; callers reuse logic, not the same state

State snapshots and batching

State is fixed within one render. When several updates depend on the previous value, give React a function that calculates the next one:

tsx
setCount((count) => count + 1)
setCount((count) => count + 1)

React batches updates from the same turn to avoid redundant renders. Calling a setter requests the next render; it does not change the variable already captured by the current function.

useEffect and the lifecycle

useEffect is not a lifecycle bucket for arbitrary logic. It synchronizes a component with systems outside React. If a value can be calculated during rendering, do not store another copy through an Effect.

tsx
useEffect(() => {
  const controller = new AbortController()

  loadUser(userId, controller.signal)
  return () => controller.abort()
}, [userId])
  • Setup runs after the first commit—similar to mounting.
  • When dependencies change, cleanup runs with old values before setup runs with new values—similar to updating.
  • Cleanup runs one final time on unmount.
  • In development, Strict Mode may run setup → cleanup → setup once more to reveal incomplete cleanup.

Component Communication and State Management

React state moves outward by sharing scope from local state to props, Context, and Zustand

Keep state as close as possible to where it is used. Lift it or move it into a global store only when several consumers genuinely need it.

Scope or relationshipPreferred approachTypical examples
One componentuseState / useReducerOpen state, a form draft
Parent to childPropsData, configuration, event handlers
Child to parentCallback propSave, delete, input changes
SiblingsLift state to their common parentA filter and its result list
One stable subtreeContextTheme, locale, auth, form context
Complex cross-page stateAn external store such as ZustandUser, permissions, cart, editor state

Controlled vs uncontrolled components

  • A controlled component gets its value from React state and writes changes back through onChange. Validation, coordination, and submission stay in one place.
  • An uncontrolled component keeps its value mainly in the DOM and is read through a ref. It suits simple forms, file inputs, or integration with non-React code.

Context, useReducer, and Zustand

  • Context solves deep value passing; it is not a complete state manager. When a Provider value changes, its consumers render again, so split large, frequently changing values.
  • useReducer suits state with several update rules inside a component or subtree. The reducer centralizes what each action means.
  • Zustand suits shared state independent of component depth. A store also works outside components, and selectors let a component subscribe only to the slice it needs.

Remember: keep local state local; props preserve one-way flow, Context crosses levels, and a store crosses pages.

React Performance

React performance work proceeds through measuring, removing work, memoizing, and deferring non-urgent updates

Use this order: measure → remove unnecessary work → cache → split or defer. Do not begin by wrapping every object and function in a memoization Hook.

TechniqueUse it when
Smaller components and local stateA parent update currently rerenders a large area
memoA child is noticeably expensive and its props usually stay the same
useMemoA calculation is measurably expensive or feeds a memoized child
useCallbackA function goes to a memoized child or is another Hook's dependency
lazy + SuspenseA page, dialog, or editor does not belong in the initial bundle
useTransitionSearch results, charts, or tab content must not block typing
List virtualizationA long list should render only rows near the viewport

memo shallowly compares props. A newly created object, array, or function is still a new reference. Do not add useMemo or useCallback only to make references look stable; they also add comparisons and code complexity.

Use React DevTools Profiler to find the actual slow component, then verify that the change helped. The goal is less real work, not more Hooks.

React Router

React Router moves from a URL through route matching and loading to nested page rendering

A client-side router watches the URL, matches a route tree, and renders the corresponding components so a single-page app can switch screens without a full reload.

Routing modes and values

ItemKey point
Browser HistoryClean URLs; the server must send index.html for unknown application paths
HashIncludes # and normally needs no server fallback configuration
ParamsPart of the path, such as /users/:id; use for resource identity
Search Params?page=2&sort=time; good for filters and pagination, shareable and refresh-safe
Location StateHidden from the URL; good for temporary navigation data, not a shareable or durable source

What matters in a real project

  • Nested routes reuse navigation, sidebars, and other shells through a parent layout and <Outlet />.
  • Lazy-load page code. A data-aware route can load data before rendering and expose a clear pending state.
  • Show a 404 for unmatched paths and use the nearest error boundary for rendering or loading failures.
  • Centralize login and permission checks in a route layout or loader. Client checks improve UX; the server must still enforce authorization.
  • Use navigate for programmatic navigation and prefer <Link> for links so accessibility and browser behavior are preserved.

Remember: the URL is part of page state. Match the route, load code and data, then render the nested page.

Part 4: Other Topics

i18n Internationalization

Known text uses a language word list, while new text goes through a translation service

Think of i18n as a fill-in-the-blank system. Remove the words from the page but keep named spaces for them. When the user chooses a language, fill those spaces from the matching language word list.

When the backend sends English, first decide which kind it is:

English contentWhat to doExamples
Fixed textThe backend returns a stable code; the frontend looks it up in the language word listButtons, menus, order statuses, error messages
Text that changes every timeThe backend calls a translation service or AI, saves the result, and returns itArticles, AI responses, user input

For example, the backend should return PAYMENT_FAILED instead of making the frontend guess what Payment failed means. The frontend can then show the matching text in any language. An “English → code” converter can temporarily support an old API, but it breaks when the English wording changes.

Tools such as Vue I18n manage the frontend's language word lists; they do not translate articles automatically. Dynamic text needs a service such as DeepL, Google Translate, or an AI model. The backend normally calls it so credentials stay private and results can be cached to control cost.

Remember: look up fixed text and translate changing text. The frontend displays it; the backend provides codes, translation, and caching.

References