# Bitlyst — full text export > Machine-readable dump of all published posts. Optional "Going deeper" panels and diagram components removed. Source: https://bitlyst.blog/llms-full.txt --- ## What Runs First in a Next.js Page: Server Components, Render, Effects URL: https://bitlyst.blog/p/react-nextjs-render-order Summary: Server first, browser second. Render goes down the tree, effects come back up. The order of every hook from request to state update, measured. Published: 2026-11-21 Tags: react, nextjs, server-components, useeffect, hooks, interview A child component's `useEffect` reads something its parent's effect was supposed to set up. It's `undefined`. You add a `console.log` to both and find the child's effect ran **first**, even though the parent rendered first. Nothing is broken. That's the order React promises. ## The mental model: down, then back up > The server goes first, the browser second. Inside the browser, render walks **down** the tree, parent before child. Effects walk back **up**, child before parent. The screen updates in between. Picture nested boxes. Rendering opens them from the outside in. Effects close them from the inside out, because a parent isn't finished until its children are. ![AI-generated illustration. The server builds the page, the HTML travels, the browser shows it, and only then does the JavaScript switch it on.](/assets/render-order-relay.jpg) ## The full order, from request to click **On the server.** Server Components run first: they fetch data and pass it down as props. Then React renders your `"use client"` components too, to turn them into HTML. That's the surprise for many people: a Client Component renders on the server. Only its effects and event handlers are skipped there. I ran a two-level tree through `renderToString` and the log showed the `useState` initializer, `useMemo`, and both render functions. No effect of any kind ran. **In the browser.** The HTML is already on screen. When the JavaScript arrives, React renders the Client Components again (this is [hydration](/p/how-ssr-works-react-nextjs)), then runs the effects. Here's the hydration log from a `Parent` that renders a `Child`, on React 19.3.1: ```txt Parent useState initializer Parent useMemo Parent render Child render Child ref attached Child useLayoutEffect Parent useLayoutEffect Child useEffect Parent useEffect ``` Inside one render, hooks run in the order you wrote them. `useState` and `useMemo` run during the render itself. Effects only run after React has updated the DOM. ## When state changes Calling `setCount(1)` repeats the browser half, with one addition: every old effect is cleaned up before any new one runs. The log, with the `useMemo` and ref lines left out: ```txt Parent render (count=1) Child render (props.count=1) Child useLayoutEffect cleanup Parent useLayoutEffect cleanup Child useLayoutEffect Parent useLayoutEffect Child useEffect cleanup Parent useEffect cleanup Child useEffect Parent useEffect ``` The parent renders first, so the child receives the new props in the same pass. A state change re-renders that component and everything under it. Nothing above it runs. ## In practice - **A parent's effect can't prepare something for a child's effect.** The child's runs first. Pass the value down as a prop, or create it during render. - **Measure the DOM in `useLayoutEffect`.** It runs after the DOM exists and before paint, so a fix doesn't flash. Everything else goes in `useEffect`. See [useEffect vs useLayoutEffect](/p/useeffect-vs-uselayouteffect). - **Don't read `window` during render in a Client Component.** It renders on the server, where `window` doesn't exist. Read it in an effect. - **Fetch in a Server Component when you can.** It runs before any browser code, so the data is in the first HTML instead of arriving after an effect. **Honest stakes:** most components never notice the order. You meet it when two effects depend on each other, when a measurement flickers, or when code that touches `window` crashes the server render. ## Say it in an interview > "In the App Router, Server Components run first on the server and pass props down. Client Components also render on the server to produce HTML, but their effects don't run there. In the browser, React hydrates: it renders top-down, parent before child, updates the DOM and attaches refs, then runs layout effects bottom-up, child before parent, before paint, and regular effects bottom-up after paint. On a state update, the cleanups for the old effects run before the new effects." ## Cheat sheet | Step | Where | Order | |---|---|---| | Server Component | Server only | First, parents before children | | Client Component render (`useState`, `useMemo`, JSX) | Server, then browser | Parent before child | | Refs attached, `useLayoutEffect` | Browser, before paint | Child before parent | | `useEffect` | Browser, after paint | Child before parent | | On update: cleanups | Browser | All old cleanups before the new effects | ## TL;DR - Server Components run first, only on the server. - Client Components render on the server too. Their effects don't run there. - Render goes down the tree. Effects come back up. - `useLayoutEffect` runs before paint, `useEffect` after it. - On an update, old effects are cleaned up before new ones run. --- ## You Don't Need That useEffect: Derived State in React URL: https://bitlyst.blog/p/react-derived-state-useeffect Summary: If you can calculate a value from props or state, it isn't state. Copying it with useEffect costs an extra render and shows a stale value first. Published: 2026-11-21 Tags: react, useeffect, state, hooks, interview A search box over a list. It works, and it shows up in code review every week: ```jsx function Results({ items, query }) { const [filtered, setFiltered] = useState(items); useEffect(() => { setFiltered(items.filter((item) => item.name.includes(query))); }, [items, query]); return ; } ``` Type a letter and the list updates. Nothing looks broken. But every keystroke renders `Results` twice, and the first render shows the old list. ## The mental model: a copy that runs late > If you can calculate it from props or state, it isn't state. Calculate it while rendering. `filtered` is a copy of an answer you already have. `items` and `query` are the source. A copy kept in its own state has to be updated after the source changes, and until then it's out of date. ![AI-generated illustration. The copy on the left trails behind its source. The view on the right reads the source directly, so it can't fall behind.](/assets/derived-state-copies.jpg) ## How the copy goes wrong Follow one keystroke through the code above: 1. `query` changes, so React renders `Results`. 2. That render still reads the old `filtered`, because the effect hasn't run yet. React puts the old list on screen. 3. After the screen updates, the effect runs and calls `setFiltered`. 4. That state change renders `Results` again, this time with the right list. I counted this with React 19.3.1. Over 5,000 items, changing the query to `"item 42"` rendered the effect version **twice**. The first render still had all **5,000** items. The second had the right **111**. Steps 2 and 3 are the [useEffect-after-paint gap](/p/useeffect-vs-uselayouteffect): a slow device can show the stale list for a frame. The fix deletes code: ```jsx function Results({ items, query }) { const filtered = items.filter((item) => item.name.includes(query)); return ; } ``` Same test, **one** render, already showing 111 items. Nothing to keep in sync, because nothing was copied. ## In practice The same pattern hides behind other names: ```jsx // before: state + effect const [fullName, setFullName] = useState(""); useEffect(() => setFullName(`${first} ${last}`), [first, last]); // after: a variable const fullName = `${first} ${last}`; ``` Totals from a cart, `isValid` from form fields, `selectedItem` from a list plus an id: each one is a value you calculate while rendering, not a value you store. If the calculation is genuinely slow, wrap it in `useMemo`. That still runs during the render, so there's no stale frame. It only skips the work when the inputs haven't changed: ```jsx const filtered = useMemo( () => items.filter((item) => item.name.includes(query)), [items, query], ); ``` Reach for an effect only when the code talks to something outside React: fetching, a subscription, a timer, the DOM. Copying one piece of React state into another isn't on that list. **Honest stakes:** with a short list you won't see the stale frame, and the extra render costs little. The real cost is bugs. Two copies of one answer drift apart: someone updates `items` from a new place, forgets the effect's dependency list, and the screen disagrees with the data. ## Say it in an interview > "If a value can be computed from props or state, I compute it during render instead of storing it. Copying it into state with useEffect means the first render uses the old value, the effect runs after paint, and its setState causes a second render. Computing it inline gives one render with the right value. If the calculation is expensive I use useMemo. Effects are for syncing with things outside React, like the network or the DOM." ## Cheat sheet | You have | Write | |---|---| | A value computed from props or state | A `const` in the component body | | The same, but slow to compute | `useMemo` with its inputs | | Data from the network | An effect, or better, a data library | | A value the user edits | `useState` | ## TL;DR - If you can calculate it, it isn't state. - `useState` plus a `useEffect` that sets it gives two renders and a stale first frame. - Calculate the value in the component body. Use `useMemo` only when it's slow. - Effects are for the world outside React, not for copying state. --- ## Boolean(x) vs !!x, Number vs parseInt, and String() vs toString() URL: https://bitlyst.blog/p/boolean-vs-bang-number-vs-parseint Summary: Boolean and !! match. Number and + match, except a BigInt. String(null) is "null"; null.toString() throws. Published: 2026-11-17 Tags: javascript, boolean, numbers, parseint, strings, performance, interview ```js Number("12px"); // NaN +"12px"; // NaN parseInt("12px"); // 12 ``` `Boolean(x)` and `!!x` get recommended as the fast spelling. So do `+x` and `parseInt`. On a million values they took the same few nanoseconds. The thing that changes the result is which tool you picked. ## The mental model: two switches, one short ruler > `Boolean(x)` and `!!x` are two spellings of one question: is this value filled in? `Number(x)` and `+x` are two spellings of another: read the whole value as a number. `parseInt` is a shorter ruler. It reads digits from the start and stops at the first character that doesn't fit. `String(x)` writes text for any value. `x.toString()` asks the value to write it, so `null` has nobody to ask. ![AI-generated illustration. The two switches match. The ruler covers only the start of the strip, which is what parseInt does with "12px".](/assets/boolean-number-coercion-tools.jpg) ## How the two spellings behave `!!x` is "not not x". Each `!` flips the answer, so two flips land on the same yes-or-no as `Boolean(x)`. Both use the language's ordinary truthiness. `0`, `""`, `null`, `undefined`, `NaN`, and `false` are empty. Everything else is filled in, including `"0"`, `"false"`, and `[]`. ```js Boolean("0"); // true !!"0"; // true Boolean(""); // false !!""; // false ``` Call `Boolean` without `new`. `new Boolean(false)` is an object, so it counts as filled in. `Number(x)` and `+x` agree on strings, booleans, `null`, and arrays. `Number("")` and `+""` are `0`. `Number("1e2")` and `+"1e2"` are `100`. `Number("12px")` and `+"12px"` are `NaN`, because the whole string has to be a number. One input splits them. A BigInt converts through `Number` and throws through `+`: ```js Number(1n); // 1 +1n; // TypeError ``` `Number` may turn a BigInt into a number, and a huge one can round. Unary `+` refuses a BigInt so an implicit conversion cannot drop digits. `parseInt` answers a third question: what integer is at the start of this text? ```js parseInt("12px", 10); // 12 parseInt("1e2", 10); // 1 the e stops it parseInt("", 10); // NaN Number(""); // 0 ``` Pass the radix. `parseInt("0x10")` is `16`, because a missing radix lets it notice the hex prefix. `parseInt("0x10", 10)` is `0`. The full set of disagreements, including `.map(parseInt)` reading the index as the radix, is in [why map(parseInt) checks the wrong rows](/p/javascript-map-parseint). ## `String()` writes the text. `toString()` asks the value ```js String(null); // "null" null.toString(); // TypeError String(undefined); // "undefined" (255).toString(16); // "ff" String has no radix ``` `String(x)` accepts every value. `null` becomes `"null"`, `undefined` becomes `"undefined"`, and `[]` becomes `""` because an array's text is its items joined with commas. `.toString()` is a method call. `null` and `undefined` have no method, so the call throws before any conversion. A symbol is the case that splits the third spelling, `x + ""`: ```js const id = Symbol("id"); String(id); // "Symbol(id)" id.toString(); // "Symbol(id)" id + ""; // TypeError ``` `String(id)` and `id.toString()` agree. Concatenation uses the ordinary string conversion, and that conversion refuses a symbol, the same way `+` refuses a BigInt. On a million numbers, `n + ""` took about 1.7 ns, `n.toString()` about 3.7, and `String(n)` about 5.3. That gap is real in a loop that only converts. It is still a few nanoseconds. The minified functions were 100 bytes for `String(x)` and 103 for `x.toString()`. ## What the speed and the bundle actually were Timed the same way, `Boolean(x)`, `!!x`, and a plain `if (x)` were about 1.7 ns. `Number(x)`, `+x`, and `parseInt(x, 10)` were about 3 ns on clean digits, and about 15 ns together on a mix that included `"12px"`, `""`, and `"1e2"`. None of them import a module. Bun's minifier left both spellings in place: `!!x` was 7 bytes shorter than `Boolean(x)`, and 2 bytes after gzip. The method is in Going deeper. ## In practice Use `Boolean`, `Number`, and `String` when you hand a function to `filter` or `map`. `!!`, `+`, and `.toString()` need an arrow: `xs.filter((x) => !!x)`, `xs.map((x) => +x)`, `xs.map((x) => x.toString())`. `xs.map(String)` survives a `null`. `xs.map((x) => x.toString())` throws on one. Give `parseInt` its own arrow and a radix, `xs.map((s) => parseInt(s, 10))`, so the index is not read as the base. Use `.toString(radix)` when you want a base other than 10. Pick `parseInt` when trailing text is expected and you want the leading integer: a CSS value, a heading like `"12px"`. Pick `Number` or `+` when the whole string must be a number and junk should become `NaN`. **Honest stakes:** you will not find a few nanoseconds in a profile, and you will not find these spellings in a bundle report. You will find `parseInt("12px")` turning into `12` in a form, `Number("")` turning into `0`, and `value.toString()` throwing because `value` was `null`. ## Say it in an interview > "`Boolean(x)` and `!!x` are the same truthiness check. `Number(x)` and `+x` both read the whole value as a number, except `Number(1n)` is `1` and `+1n` throws. `parseInt` stops early, so `parseInt("12px", 10)` is `12` while `Number("12px")` is `NaN`. `String(null)` is `"null"`, and `null.toString()` throws because there is no method to call. On Node 26 the boolean and number spellings were the same few nanoseconds. `String(n)` was slower than `n.toString()` in a tight loop, still about 5 ns, and I still pick the one that handles `null`." ## Cheat sheet | Input | `Boolean` / `!!` | `Number` / `+` | `parseInt(x, 10)` | |---|---|---|---| | `"12"` | `true` | `12` | `12` | | `"12px"` | `true` | `NaN` | `12` | | `""` | `false` | `0` | `NaN` | | `"1e2"` | `true` | `100` | `1` | | `1n` | `true` | `Number`: `1`, `+`: throws | `1` | | Input | `String(x)` | `x.toString()` | `x + ""` | |---|---|---|---| | `null` | `"null"` | throws | `"null"` | | `undefined` | `"undefined"` | throws | `"undefined"` | | `255` in base 16 | no radix argument | `"ff"` | `"255"` | | `Symbol("id")` | `"Symbol(id)"` | `"Symbol(id)"` | throws | ## TL;DR - `Boolean(x)` and `!!x` ask the same question. Call `Boolean` without `new`. - `Number(x)` and `+x` read the whole value as a number. `Number(1n)` works. `+1n` throws. - `parseInt` stops at the first bad digit. `"12px"` becomes `12`. Pass a radix. - `String(null)` is `"null"`. `null.toString()` throws. `.toString(16)` is how you get `"ff"`. - Boolean and number spellings took the same few nanoseconds. `String(n)` was about 5 ns, `n.toString()` about 4, `n + ""` about 2. The bundle gap was a handful of bytes. --- ## satisfies, as, as const, and is: How TypeScript Labels a Value URL: https://bitlyst.blog/p/typescript-satisfies-as-const Summary: as const keeps the exact value. satisfies checks a type and keeps it. as replaces the type. is narrows it when a check returns true. Published: 2026-11-17 Tags: typescript, satisfies, as-const, types, interview ```ts type Config = { mode: "dark" | "light"; home: `/${string}` }; const config: Config = { mode: "dark", home: "/" }; config.mode; // "dark" | "light" — the exact "dark" is gone config.home; // `/${string}` — the exact "/" is gone ``` You wrote `"dark"` and `"/"`. The annotation stored the whole allowed set. A function that only accepts `"dark"` now rejects `config.mode`. ## The mental model: a name tag > TypeScript likes a general label. `as const` laminates the exact letters. `satisfies` checks your value against a type, then hands the original tag back. `as` writes a new tag, and the new tag can be a lie. `is` hands over a new tag only when a function returns true. A bare `const` string is already exact: `const home = "/"` has the type `"/"`. Objects are where the letters disappear. With no annotation, `{ mode: "dark" }` is `{ mode: string }`. ![AI-generated illustration. The lock keeps the exact letters, the stamp checks them, and the blank sticker is a label you wrote yourself.](/assets/satisfies-as-const-tags.jpg) ## `as const` laminates the exact value ```ts const routes = { home: "/", about: "/about", } as const; routes.home; // "/" routes.home = "/nope"; // error: readonly ``` The type is `{ readonly home: "/"; readonly about: "/about" }`. `(typeof routes)[keyof typeof routes]` is then `"/" | "/about"`, the usual stand-in for an enum. A list works the same way: `["red", "green"] as const` is `readonly ["red", "green"]`. That pattern is the one in [TypeScript enums vs alternatives](/p/typescript-enums-vs-alternatives). ## A type annotation replaces the label ```ts const config: Config = { mode: "dark", home: "/" }; config.mode; // "dark" | "light" ``` The `: Config` checks the object. A missing key is an error, and so is `mode: "nope"`. After the check, the variable's type **is** `Config`. `"dark"` has been replaced by `"dark" | "light"`, and `"/"` by "a string that starts with `/`". ## `satisfies` checks, then hands the label back ```ts const config = { mode: "dark", home: "/" } satisfies Config; config.mode; // "dark" config.home; // "/" ``` `Config` is the guest list. `"dark"` has to be one of the modes, `home` has to start with `/`, and an extra key is an error. Then the original letters stay. `config.mode` is `"dark"`, so it passes a function that only accepts `"dark"`. Assigning `"light"` later is an error: the property's type is the literal `"dark"`, even though `Config` allows both. If the property in `Config` is a plain `string`, `satisfies` widens it to `string` too. The exact letters survive when that type is a union of literals, a template literal type like `` `/${string}` ``, or when you laminate first: ```ts const config = { mode: "dark", home: "/" } as const satisfies Config; ``` `as const` runs first, then `satisfies` checks the frozen value. The result is readonly, and it still has to match `Config`. ## `as` writes a new label ```ts const mode = "nope" as "dark" | "light"; // no error mode; // "dark" | "light" ``` Both sides are strings, so the checker steps aside. The type says `"dark" | "light"`. The value at runtime is still `"nope"`. Nothing throws. Use `as` where a value enters typed code from outside it: `JSON.parse(text) as Config`, or a DOM node you already proved is there. The proof is yours. The checker will not repeat it. ## `is` narrows when a check returns true ```ts function isDark(value: unknown): value is "dark" { return value === "dark"; } if (isDark(input)) { input; // "dark" } ``` `value is "dark"` is a type predicate. In the true branch, `input` wears that label. The same annotation on a `filter` callback is why the result becomes `"dark"[]` instead of `unknown[]`: ```ts const darks = items.filter((item): item is "dark" => item === "dark"); ``` The checker trusts the predicate. A function that `return true`s still compiles, and the true branch still narrows. The `===` is the part that protects you. ## In practice Use `as const` on route maps, option lists, and config you want as a union. Use `satisfies` when an object must match a shape and you still want the specific values. Use `as const satisfies` when you want both the shape check and the readonly literals. Save `as` for a boundary you have already proved. For `unknown`, write an `is` function whose body does the check, and narrow with that. **Honest stakes:** `as`, `as const`, and `satisfies` are erased when TypeScript becomes JavaScript. They cannot catch a bad value at runtime. A wrong `as` compiles and fails later, on a property that is not there. The `is` in a predicate is erased too, and the function body still runs, so the check is real if you wrote one. You will type `as const` most weeks. `satisfies` shows up on config objects. A file full of `as` usually means a missing predicate. ## Say it in an interview > "`as const` keeps the exact literal and makes it readonly. An annotation checks a value and then the variable's type becomes that annotation, while `satisfies` checks and keeps the specific type. `as` replaces the type without a check when the two types overlap, so it can be wrong, and it disappears at runtime. `is` is a function return type: when the function returns true the argument narrows, and the function body is what still runs." ## Cheat sheet | | What the variable's type becomes | Catches a bad value? | At runtime | |---|---|---|---| | `as const` | The exact literals, marked readonly | No. It only freezes what you wrote | Erased | | `: Config` | `Config` | Yes | Erased | | `satisfies Config` | The exact value, which must be a `Config` | Yes | Erased | | `as Config` | `Config` | Only when the two types do not overlap | Erased | | `value is Config` | The argument becomes `Config` when the function returns true | Only the check in the function body | The function runs. The `is` type is erased | ## TL;DR - Objects and arrays widen. `{ mode: "dark" }` is `{ mode: string }`. A bare `const` string stays `"dark"`. - `as const` keeps the exact literals and marks them readonly. - An annotation checks the value, then the variable's type becomes the annotation. - `satisfies` checks the value and leaves the exact type in place. - `as` overwrites the type. `"nope" as "dark"` compiles, and the value is still `"nope"`. - `value is "dark"` narrows the argument in the true branch. The function body is the runtime check. --- ## Barrel Files (`index.ts`): Why One Import Can Slow Your Build URL: https://bitlyst.blog/p/barrel-files-index-ts Summary: A barrel re-exports a whole folder. Tree shaking may still drop unused code, but the bundler often walks every file behind that index first. Published: 2026-11-16 Tags: typescript, bundler, performance, barrel-files, tree-shaking You add a tidy folder: ten components, one `index.ts` that re-exports them all, and a single import line in the app: ```ts import { Button } from "@/components/ui"; ``` You only wanted **Button**. The dev build still feels heavier than it should. ## The mental model: the whole shelf > A **barrel file** is an `index.ts` that re-exports a folder so you can import from one path. It's convenient. It's also like asking the library for **one book** and having the librarian pull **every book on that shelf** into the room before they hand you the right one. The bundler's job is to follow every `export * from` and `export { X } from` while it figures out what your entry file actually needs. Tree shaking can still drop unused code from the final bundle. The work of **reading and linking** the rest of the shelf often happens anyway. ![AI-generated illustration. One index card fans out to many modules behind it.](/assets/barrel-files-barrel.jpg) ## How it works A typical barrel: ```ts // components/ui/index.ts export * from "./button"; export * from "./dialog"; export * from "./data-table"; ``` Each file may import heavy packages: ```ts // data-table.ts import { LineChart } from "recharts"; export function DataTable() { /* ... */ } ``` Your page only imports `Button`: ```ts import { Button } from "@/components/ui"; ``` Modern bundlers (esbuild, Rollup, Turbopack, webpack) **can** leave `DataTable` and `recharts` out of the shipped JavaScript if nothing references them. The catch is what they must **walk** to be sure. I measured a tiny demo on my machine with esbuild 0.25, three modules behind one barrel (`lodash/get`, `date-fns/format`, `recharts`), and one entry file that imports only `pickA` from the barrel: | Import path | Modules esbuild had to read | Minified bundle | esbuild time | |---|---:|---:|---:| | `./direct/a` (no barrel) | 54 | 8.4 KB | 5 ms | | `./barrel` (re-export all) | 471 | 8.4 KB | 43 ms | Same shipped size. **About eight times more files parsed**, and **about eight times longer** to bundle that one entry, because the barrel pulled the resolver through every re-exported file and its dependencies. That gap is what you feel in a big app: slower first compile, slower HMR, TypeScript and ESLint spending time on modules you never imported at runtime, and CI builds that redo the same graph on every push. Barrels hurt more when: - **Side effects** at the top of a re-exported file (`import "./polyfill"`) force those modules to stay in the bundle even if you never call them. - **Libraries** ship their own barrels (`@mui/material`, some icon packs) so deep imports are the documented fix. - **Monorepos** nest barrels (`packages/ui/index.ts` → ten more `index.ts` files) and multiply the graph. ## In practice Keep barrels for **public package APIs** you publish to npm. Inside an app, prefer **direct imports** on hot paths: ```ts // before import { Button } from "@/components/ui"; // after import { Button } from "@/components/ui/button"; ``` If you like the short path, use a **subpath** in `package.json` (`"exports"`) instead of a giant `export *` file. Your editor and bundler then resolve one file, not a fan-out. Run your own check when a folder grows past a handful of files: build one route with the barrel import and again with a direct import, compare the bundler's module count or build time. You don't need a guess. The shelf either shows up in the stats or it doesn't. Honest stakes: on a ten-file hobby project, you may never notice. On a design-system folder imported from hundreds of routes, barrels are a common reason **cold `next dev` and CI builds** feel slower than the code changed. > **Say it in an interview:** A barrel file re-exports a folder from one `index.ts` so imports look clean. Tree shaking can still drop unused exports from the final bundle, but the bundler usually has to parse and analyze every re-exported module first. That's extra build work and can pull in side effects. I reach for direct imports or package `exports` maps on hot paths, and keep barrels for library public APIs. ## Cheat sheet | What you write | What often happens | |---|---| | `import { Button } from "./ui"` via `index.ts` | Resolver walks every file the barrel re-exports | | Same runtime bundle as direct import | Often yes, when tree shaking works | | Same build cost as direct import | Often no: more files parsed and typed | | `export *` + side-effect imports | Unused modules can still ship | | Fix on hot paths | Import the file directly or use `exports` subpaths | --- ## Hoisting and the TDZ: Why let Throws and var Is undefined URL: https://bitlyst.blog/p/hoisting-and-tdz Summary: var and let are both registered when the scope starts. var is already undefined. let stays untouchable until its line runs. Published: 2026-11-16 Tags: javascript, hoisting, tdz, let, var, interview ```js console.log(a); // undefined var a = 1; ``` ```js console.log(b); // ReferenceError let b = 1; ``` Both names exist before those lines. Only one of them lets you touch it. ## The mental model: a rope in front of the name When a scope starts, JavaScript registers every name declared inside it. The assignments stay where you wrote them. Nothing is moved to the top of the file. > `var` is registered as `undefined`, so reading it early is safe and useless. `let` is registered too, but it sits behind a rope until its line runs. Touching it early throws. That rope is the **temporal dead zone**. Temporal means time: from the moment the scope starts until the declaration line runs. ![AI-generated illustration. The name behind the rope already exists. Touching it before its line runs is what throws.](/assets/hoisting-tdz-rope.jpg) ## How it works Hoisting is that early registration. People picture the engine cutting the `var` line and pasting it at the top. It doesn't. The name is created up front. The `= 1` stays put. ```js function demo() { console.log(x); // undefined if (false) { var x = 1; // this assignment never runs } } ``` `x` becomes `undefined` when `demo` starts, even though the `var` sits in an `if` that never runs. `var` is function-scoped: one registration for the whole function, ignoring the block. `let` and `const` are block-scoped, and they start with no value: ```js { console.log(y); // ReferenceError let y = 1; // the rope drops here } ``` Before that line, `y` has a name and nothing you may read. Reading it, writing it, even `typeof y`, throws `ReferenceError`. After the line, `y` is `1`. `const` uses the same rope. Its line must set the value, and you can't assign a new one later. `typeof` is the proof that the name is real and still forbidden: ```js typeof missing; // "undefined" — there is no such binding typeof later; // ReferenceError — the binding exists, the rope is up let later = 1; ``` A name that was never declared is a quiet `"undefined"`. A `let` you haven't reached yet is an error, because the scope already knows the name. ## In practice Declare `let` and `const` before any line in that block that reads them. If the value isn't ready, compute it first, then declare. Prefer them to `var`. The throw is the useful part. `var` handing back `undefined` lets a bug travel, and you meet it later as a wrong value. **Honest stakes:** you'll hit the rope when one block reads a `const` declared further down, or when an inner `let` reuses a name from outside. Declaring at the top of the block means you won't see it in ordinary code. Interviews ask anyway, because the two answers look almost the same until you say when the value appears. ## Say it in an interview > "var and let are both hoisted: the name is registered when the scope starts, and the assignment stays on its line. var is initialized to undefined, so reading it early gives undefined. let and const stay uninitialized until their line runs. That gap is the temporal dead zone, and touching the name throws ReferenceError. typeof on a missing name is undefined, but typeof on a let still in the zone throws, because the name exists." ## Cheat sheet | | var | let and const | |---|---|---| | Registered when | The function starts | The block starts | | Before its line | `undefined` | No value. Don't touch it | | Read it early | `undefined` | `ReferenceError` | | Scope | The whole function | The block | | `typeof` before its line | `"undefined"` | `ReferenceError` | ## TL;DR - The name is registered when the scope starts. The assignment stays on its line. - `var` starts as `undefined`. Reading it early does not throw. - `let` and `const` stay behind the rope until their line runs. Touching them throws `ReferenceError`. - `typeof` on a name that doesn't exist is `"undefined"`. `typeof` on a `let` still behind the rope throws. --- ## How Garbage Collection Works: It Never Looks for Unused Memory URL: https://bitlyst.blog/p/how-garbage-collection-works Summary: The collector paints every object reachable from the stack and globals. Whatever the paint misses is unused, even if objects still point at each other. Published: 2026-11-16 Tags: javascript, garbage-collection, memory, v8, interview Picture two snippets that feel like they should do the opposite. ```js let a = {}; let b = {}; a.friend = b; b.friend = a; a = null; b = null; // both objects can be freed, even though each still points at the other ``` ```js function load() { const pages = new Array(100_000).fill("page"); return () => pages.length; } const size = load(); // this little function keeps the whole array alive ``` The pair that only points at itself can be thrown away. The tiny function keeps 100,000 strings. The collector is not searching for things you finished with. It is searching for what the program can still reach. ## The mental model: paint from the roots Your code never grabs an object out of thin air. It starts from something it already holds and follows references: a property, an array slot, a variable a function closed over. Those starting points are the **roots**. A local variable in a function that's running is a root. So is a global. > The collector paints every object it can reach by following references from the roots. Whatever the paint misses is unused, because no future line of code can touch it. ![AI-generated illustration. A handshake with nothing else attached is already unused. A function you kept is a root, so the stack it closes over stays.](/assets/gc-reachability-roots.jpg) ## How it works The walk is called **marking**. Start at the roots. From each object, visit every reference, and paint the object at the other end. A cycle doesn't help the pair above: `a` and `b` point at each other, but after both variables are `null`, no root leads in, so the walk never enters. Then the engine reclaims everything with no paint. It does not need a list of "deleted" objects. Unreachable memory is unused by definition. V8 does the reclaim in two different ways, depending on the object's age. In the young space it copies the painted objects out and abandons the rest of the room. In the old space it sweeps the unpainted ones. What that copying costs is the subject of [why middle-aged objects are expensive](/p/v8-garbage-collector-survivors). This post is only the decision that comes first: painted or not. You don't free an object. You drop the last path from a root. ```js let user = { name: "Ada" }; user = null; // the object is now unreachable ``` `delete user.name` is different. It removes one property. The object stored in `user` is still reachable through the variable. ## In practice A leak is a root you forgot about. The object looks finished, and something still reaches it: - A module-level cache, array, or `Map` that only ever grows. - A `setInterval` or an event listener whose callback closes over a big object, and that you never clear. - A function you stored, like `size` above, which quietly keeps every variable it closed over. When a long-lived page's memory climbs, a heap snapshot shows the **retainer path**: the chain of references from a root to the object you expected to be gone. That chain is the bug. The object itself is doing what the rule says. **Honest stakes:** a script that runs and exits rarely makes you care. You'll meet this on a page or a server process that stays up, when one forgotten root keeps appending. Short-lived objects, the ones nobody keeps a reference to, are the ones the collector handles without your help. ## Say it in an interview > "The garbage collector doesn't look for unused objects. It starts from roots, the call stack and globals, and marks every object it can reach by following references. Anything unmarked is unreachable, so the program can never use it again, and the memory can be reused. A cycle with no outside reference is still garbage. A closure you kept can keep a large object alive. You free memory by dropping the last path from a root, not by calling delete." ## Cheat sheet | | What it means | |---|---| | Root | A starting point: a live local variable, or a global | | Mark | Follow every reference from the roots and paint what you reach | | Unpainted | Unreachable. No code can touch it. The memory can be reused | | A cycle | Still garbage, if nothing outside the cycle is a way in | | A closure you kept | A root. Everything it closed over stays alive | | How you free something | Drop the last path from a root | ## TL;DR - The collector paints what it can reach from the stack and from globals. - Anything the paint misses is unused, even if those objects still point at each other. - A function you kept alive keeps every variable it closed over. - You don't free objects. You drop the last reference that a root can follow. --- ## useEffect vs useLayoutEffect: Why the Tooltip Flashes, Then Jumps URL: https://bitlyst.blog/p/useeffect-vs-uselayouteffect Summary: useEffect runs after the browser paints. useLayoutEffect runs before that paint, so a measurement can fix the screen before anyone sees the wrong frame. Published: 2026-11-15 Tags: react, hooks, useEffect, useLayoutEffect, interview Picture a tooltip that should sit above a button. For one frame it shows up at the top of the box, then it jumps into place. The measurement was right. It ran too late. `useEffect` let the browser paint the first, wrong position. ## The mental model: before the curtain, or after React updates the DOM, then the browser paints what the user sees. There is a gap between those two, like the moment before a curtain opens. > `useLayoutEffect` runs in that gap, while the curtain is closed. `useEffect` runs after the curtain opens, once the user can already see the frame. Both take the same arguments: a setup function, a dependency list, and an optional cleanup. The only difference is **when** the setup runs. ![AI-generated illustration. A fix made while the curtain is closed never becomes a flash. A fix made after it opens does.](/assets/useeffect-layout-curtain.jpg) ## How it works `useEffect` is the one for work that talks to the outside world: a fetch, a subscription, a timer, a log line. The browser paints first, so the effect doesn't hold the frame up. The user sees the new UI, then the effect runs. `useLayoutEffect` is for the case where that first paint would be a lie. You need a number the browser only knows after layout, such as a height from `getBoundingClientRect`, and you need to change what's on screen with it. ```jsx useEffect(() => { const { height } = tipRef.current.getBoundingClientRect(); setTop(buttonBottom - height); // one frame at top: 0, then it jumps }, [buttonBottom]); ``` Swap in `useLayoutEffect` and that `setTop` is flushed **before** the browser paints. React may render the tooltip twice, first at `top: 0` and then at the measured spot. The user only sees the second render. That correction is also the cost. The code inside `useLayoutEffect`, and any state update it schedules, **blocks the paint**. A slow one delays the frame. [The React docs](https://react.dev/reference/react/useLayoutEffect) say to prefer `useEffect` unless that blocking is the point. The dependency list works the same on both. It still decides when the effect re-runs, and a stale value is still stale. Timing doesn't change that. The rules are in [useEffect dependencies](/p/react-useeffect-dependencies). ## In practice Start with `useEffect`. Move to `useLayoutEffect` only after you've seen a flash. The flash shows up when you **read layout and then write the screen**: - A tooltip or menu that must flip above or below, depending on the space left. - A textarea whose height follows its content. - Scrolling or focusing an element before the user sees it in the wrong place. Leave fetching, subscriptions, and logging on `useEffect`. They don't change the frame that's about to paint. Running them in `useLayoutEffect` makes that paint wait for work the user didn't need to wait for. **Honest stakes:** most components never measure the DOM. You'll want `useLayoutEffect` a handful of times, usually on something floating. Reaching for it to be safe makes the first paint slower. Wait until something flickers. ## Say it in an interview > "useEffect and useLayoutEffect take the same arguments. useLayoutEffect runs after React commits DOM changes and before the browser paints, so you can measure layout and correct it without a visible flash. useEffect runs after the paint, so it doesn't block the frame. State updates inside useLayoutEffect are flushed before that paint. Default to useEffect, and switch only when the user would otherwise see one wrong frame." ## Cheat sheet | | useEffect | useLayoutEffect | |---|---|---| | When it runs | After the browser paints | After the DOM update, before the paint | | Blocks the paint? | No | Yes | | Use it for | Fetch, subscribe, log | Measure layout, then fix what the user would see | | A state update inside | Shows up on a later frame | Flushed before the paint | | The default | This one | Only after you've seen a flash | ## TL;DR - `useLayoutEffect` runs before the paint. `useEffect` runs after it. - The layout version can measure the DOM and correct it before anyone sees the wrong frame. - That correction blocks the paint, so a slow one delays the frame. - Start with `useEffect`. Switch when something flickers. --- ## XSS vs CSRF: Two Browser Attacks With Two Different Fixes URL: https://bitlyst.blog/p/xss-vs-csrf Summary: XSS runs the attacker's code on your page. CSRF makes the browser send a request you didn't mean to. Each cookie flag stops only one of them. Published: 2026-11-14 Tags: xss, csrf, security, cookies, interview Picture two bugs that both end with the user doing something they didn't mean to. A comment on your site renders this: ```html ``` A page on another site does this: ```html
``` Both ride the victim's browser. Against a normal session cookie, **only the first one still works.** They are different attacks, and the fix for one does nothing for the other. ## The mental model: inside the page, or only borrowing the browser **XSS** (cross-site scripting) means the attacker's code runs **on your origin**, as if you had written it. It can read the page, change it, and call your API. **CSRF** (cross-site request forgery) means the attacker's code stays **on their origin**. It tricks the browser into sending a request to you, and the browser attaches the user's cookies. The attacker never sees the response. > XSS is the attacker sitting at the keyboard on your site. CSRF is the attacker dropping a letter into the mailbox the browser already delivers. ![AI-generated illustration. One of them is already on your origin. The other never gets in, and only needs the browser to deliver the cookie.](/assets/xss-csrf-letter.jpg) ## How it works The browser's **same-origin policy** is the wall between sites. JavaScript on `evil.example` cannot read a page or a response from `yourapp.example`. XSS climbs over that wall by becoming part of your page. Once the script runs on your origin, the wall doesn't apply: the DOM and `fetch("/api/me")` are allowed. For that tab, the script **is** your site. CSRF doesn't climb the wall. A form on one site can POST to another, and the browser attaches the session cookie if the user is logged in. The attacker's page still can't read the reply, so CSRF forges an **action**, not a look at the page. The two flags from [HttpOnly cookies](/p/httpOnly-cookies-guide) point opposite ways: | Flag | Against XSS | Against CSRF | |---|---|---| | `HttpOnly` | The script can't read the cookie | No help. The browser sends it anyway | | `SameSite=Lax` | No help. The script is already on your site | The cookie stays home on a cross-site POST | `HttpOnly` limits XSS to the open tab. The script can still `fetch("/api/transfer")` and read the response, but it cannot copy the token out. `SameSite=Lax` limits CSRF, and browsers default a missing `SameSite` to `Lax`, so the form above no longer carries the session. [CORS](/p/cors-explained-simple) doesn't help: it only decides whether JavaScript may **read** a cross-origin response, and the forged form never reads one. ## In practice Stop XSS by never letting untrusted text become code. React already escapes text in JSX: ```jsx

{comment.body}

// "" shows up as text, not as a tag ``` The holes are where you opt out: `dangerouslySetInnerHTML`, `element.innerHTML`, and HTML built as a string on the server. Escape on the way **out**, for the spot you're writing into: HTML text, an attribute, or a URL. A check on the way in misses the value that looks harmless until it lands in `src`. Stop CSRF by not treating every cookie-bearing request as intent. - Session cookie: `HttpOnly; Secure; SameSite=Lax`. - State changes go on `POST`, `PUT` or `DELETE`. `Lax` still sends the cookie when someone clicks a cross-site link, and a link is a GET. - If a cookie has to be `SameSite=None` (a widget embedded on other sites), add a **CSRF token**: a secret rendered in your page that a foreign form can't read, sent back with the action, and checked on the server. **Honest stakes:** with `Lax` as the default, that cross-site form POST rarely carries a normal session cookie. XSS is the bug you'll actually ship, usually through one HTML sink. CSRF comes back when you set `SameSite=None`, or when a GET request changes data. ## Say it in an interview > "XSS is the attacker's JavaScript running on your origin, so it can read the page and call your API as the user. CSRF is a request the browser sends to your site from another site, cookies attached, while the attacker can't read the response. Escaping output stops XSS, because untrusted data never becomes code. SameSite=Lax stops most CSRF; if the cookie must be sent cross-site, add a CSRF token the foreign page can't see." ## Cheat sheet | | XSS | CSRF | |---|---|---| | Where the code runs | On your origin | On the attacker's origin | | What they get | The page, and API calls as the user | A state change, not the response | | `HttpOnly` | Blocks token theft, not the action | Does nothing | | `SameSite=Lax` | Does nothing | Blocks the cookie on a cross-site POST | | The fix | Escape output. Don't put user text in `innerHTML` | `SameSite`, no state-changing GET, a CSRF token when Lax isn't enough | ## TL;DR - XSS runs the attacker's code on your page. CSRF only borrows the browser to send a request. - `HttpOnly` limits XSS. `SameSite` limits CSRF. Each flag is useless against the other attack. - React's `{text}` is already escaped. The bug hides in `dangerouslySetInnerHTML` and raw HTML. - Cookies default to `SameSite=Lax`, so classic CSRF is rare unless you opt out or change state on GET. --- ## A Philosophy of Software Design Summary: Deep Modules Beat Small Ones URL: https://bitlyst.blog/p/a-philosophy-of-software-design-book-summary Summary: John Ousterhout's book in one sitting: complexity is the enemy, deep modules fight it, and 10–20% of your time should go to design. Five ideas to use on Monday. Published: 2026-11-13 Tags: books, software-design, architecture, clean-code, complexity Picture a codebase where adding one field means editing seven files, and nobody is sure which seven. No single commit made it that way. It got there one reasonable shortcut at a time. That slow slide is what this book is about. *Book: A Philosophy of Software Design, John Ousterhout (2nd edition, 2021).* Ousterhout is a Stanford professor who created the Tcl language, and the book grew out of a software design course he teaches there. --- ## The book in one sentence > Complexity is the enemy, and the best weapon against it is modules that hide a lot behind a simple interface. Everything else in the book either explains where complexity comes from or gives you a way to hide it. --- ## Idea 1: Complexity is anything that makes code hard to change Ousterhout defines complexity by its effect: **anything that makes a system hard to understand or modify.** He names three symptoms: - **Change amplification:** one small change needs edits in many places. - **Cognitive load:** you have to hold a lot in your head to make a change safely. - **Unknown unknowns:** you can't even tell *what* you need to change. This is the worst one. And two causes: **dependencies** (code that can't be understood alone) and **obscurity** (important information that isn't obvious). The key point: complexity is **incremental**. No single shortcut ruins a codebase, so every shortcut feels fine. **Use it:** in code review, ask "does this make the next change harder?" instead of "does this work?" --- ## Idea 2: Be strategic, not tactical **Tactical programming** means getting the current feature working as fast as possible. **Strategic programming** means treating working code as not enough: the real goal is a design that keeps future changes cheap. The book's name for the extreme tactical developer is the **tactical tornado**: someone who ships features fast and leaves a mess for everyone else, often while being praised as the most productive person on the team. Ousterhout's suggestion is modest: spend about **10–20% of your development time** on design improvements. Not a rewrite, just a steady investment that pays back within months. **Use it:** when you touch a file, leave its design slightly better than you found it, and count that as part of the task. --- ## Idea 3: Deep modules beat shallow ones This is the idea the book is known for. Think of a module (a function, class or service) as a rectangle. The **top edge is its interface**: what you must learn to use it. The **area is its functionality**: what it does for you. - A **deep module** has a small interface and a lot of functionality. The book's classic example is Unix file I/O: a handful of calls (`open`, `read`, `write`, `lseek`, `close`) hide disks, caching, permissions and file systems. - A **shallow module** has an interface almost as complex as what it does. Calling it saves you little. ![A deep module is a light switch: one simple control in front, all the wiring hidden in the wall. Photo: Kurtkaiser, CC0, via Wikimedia Commons](/assets/aposd-light-switch.jpg) Here's the difference in TypeScript (this example is not from the book): ```ts // shallow: three calls, and the caller must know the order and the format const raw = readFileSync(path, "utf8"); const parsed = parseJson(raw); const config = applyDefaults(parsed); // deep: one call, the rest is hidden const config = loadConfig(path); ``` The book also names the failure mode of "small is always good": **classitis**, where a codebase splits into many tiny classes, each easy to read alone but with so many interfaces that the system as a whole is harder to learn. **Use it:** judge a function by how much it hides, not by how short it is. --- ## Idea 4: Hide information, and watch for leaks Each module should own a **design decision** (a file format, a protocol, a caching rule) so the rest of the code doesn't need to know it. That's **information hiding**. The opposite is **information leakage**: the same decision shows up in several places. If two modules both know the layout of a file, changing the layout means changing both. A common cause is **temporal decomposition**: splitting code by the order things happen ("read, then process, then write") instead of by what knowledge each part owns. The reader and writer end up sharing the format. **Use it:** before splitting a module, ask "what knowledge does each piece own?" If the answer is "the same thing", keep them together. --- ## Idea 5: Define errors out of existence Every error a function can throw is part of its interface, and every caller has to deal with it. So the best error handling is often an API where the error **can't happen**. JavaScript has good examples (these are not from the book): ```js "abc".slice(1, 100); // "bc" ← clamps instead of throwing new Set([1]).delete(5); // false ← "make sure 5 isn't there" always succeeds ``` The book's own example is a Tcl command Ousterhout regrets designing: removing a variable that didn't exist threw an error, so callers wrapped it in error handling. Defining it as "make sure this variable doesn't exist" would have removed the error entirely. **Use it:** when you add a `throw`, ask whether a different definition of the operation would make the case normal instead. --- ## Where it's weak - **It disagrees with Clean Code, and both sides have a point.** Ousterhout argues that very short functions and "self-documenting code with no comments" often make systems harder to understand. Robert Martin disagrees. The two discussed it at length in [a public conversation](https://github.com/johnousterhout/aposd-vs-clean-code) from 2024–2025. Read both before adopting either as a rule. - **"Deep" can be misread as "big".** A 2,000-line class with a two-method interface is deep, and also hard to work on. The book wants deep *and* well organized inside. - **It's light on testing.** It's skeptical of test-driven development, arguing it pulls attention toward getting features working rather than finding the best design. Many teams won't agree. - **Few web examples.** Most examples come from systems code and student projects. You'll need to translate them to frontend work yourself. --- ## Use it on Monday 1. In your next PR, name one place where you **hid** something from callers. 2. Find a function whose callers always call two other functions right after it. Merge them into one **deep** call. 3. Pick one `throw` in your code and see if a broader definition removes it. 4. Before building a module, sketch **two** different interfaces and compare them. The book calls this "design it twice". 5. Write the comment for a function's interface **before** the code. If the comment is hard to write, the design isn't clear yet. --- ## Say it in an interview > "I like Ousterhout's idea of deep modules: a good abstraction has a simple interface and hides a lot of functionality behind it. Complexity shows up as change amplification, cognitive load and unknown unknowns, and it builds up one shortcut at a time, so I try to work strategically: spend some of every task improving the design, hide design decisions inside one module, and design APIs so common error cases simply can't happen." --- ## Cheat sheet | Idea | In one line | |---|---| | Complexity | Anything that makes code hard to understand or change | | Strategic programming | Working code isn't enough; invest 10–20% in design | | Deep modules | Small interface, lots of functionality | | Information hiding | One module owns each design decision | | Errors out of existence | Define operations so the error case can't happen | ## Should you read it? **Read it if** you've written code for a year or more and feel your designs get messy as they grow. It's short, a weekend's reading, and written plainly. **Short on time?** Read the chapters on complexity, deep modules, information hiding and errors. That's most of the value. **Skip it if** you want a catalog of patterns or framework advice. It's about how to think, not what to type. The author's page for the book: [A Philosophy of Software Design](https://web.stanford.edu/~ouster/cgi-bin/book.php). --- ## React Server Components vs 'use client': What Actually Ships to the Browser URL: https://bitlyst.blog/p/react-server-components-vs-use-client Summary: Server Components send the result; Client Components send the result plus the code. What 'use client' really does, why it doesn't mean browser-only, and where to put it. Published: 2026-11-13 Tags: react, nextjs, server-components, use-client, performance Add a log to a Client Component: ```tsx "use client"; export function LikeButton() { console.log("rendering LikeButton"); // shows up in your terminal too return ; } ``` Load the page, and the message appears in the **terminal where Next.js runs**, not just in the browser console. So `"use client"` doesn't mean "runs only in the browser". It means something else, and once you see what, it's clear where to put it. --- ## The mental model: the result vs the result plus the code Both kinds of component render on the server first, so the browser gets real HTML. The difference is what gets sent along with it: > A Server Component sends only its **result**. A Client Component sends its result **plus the code** to run it again in the browser. The result is enough to *look* at. The code is what lets a component *react*: to clicks, typing, state and effects. ![Sheet music is enough to read a song. To play it, you need the mechanism too, and that's what a Client Component ships. Photo: Jennifer Schug, CC BY-SA 4.0, via Wikimedia Commons](/assets/rsc-music-box.jpg) --- ## How it works In the Next.js App Router, **every component is a Server Component by default.** **A Server Component** runs only on the server, at build time or per request. It can be `async`, read a database or a file, and use secret keys. Its result is sent to the browser. **Its code is never sent.** A heavy library used only inside a Server Component adds zero bytes to your bundle. **A Client Component** also renders on the server for the first HTML. Then its JavaScript is downloaded and React **hydrates** it: attaches event handlers and starts its state, so the HTML becomes interactive. **`"use client"` marks a boundary.** The file with the directive, and **everything it imports**, goes into the browser bundle. You only write it at the entry point. The components it imports are client code automatically. | | Server Component | Client Component | |---|---|---| | Renders on the server | yes | yes (first HTML) | | Its code sent to the browser | no | yes | | `async`, database, secrets | yes | no | | `useState`, `useEffect`, `onClick` | no | yes | | Browser APIs (`window`, `localStorage`) | no | yes, in effects and handlers | ### Data crossing the boundary Props passed from a Server Component to a Client Component have to travel over the network, so they must be **serializable**: strings, numbers, plain objects, arrays, dates, and a few more. A regular function can't be sent: ``` Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". ``` ### Server Components can sit inside Client Components A Client Component can't *import* a Server Component, but it can *receive* one as `children`: ```tsx // page.tsx (Server Component) {/* still a Server Component: its code stays on the server */} ``` `` is rendered on the server, and `Modal` only gets its result. That's how a client-side wrapper (a modal, a tab panel, a theme provider) can hold server-rendered content. --- ## In practice **Push `"use client"` down to the leaves.** The usual mistake is putting it at the top of a whole page because one button needs `onClick`: ```tsx // before: page.tsx "use client"; // the whole page and all its imports now ship to the browser ``` ```tsx // after: page.tsx stays a Server Component import { LikeButton } from "./LikeButton"; // only this file has "use client" export default async function Page() { const post = await getPost(); return (

{post.title}

); } ``` Now only the button's code ships. The page, the data fetching and everything `PostBody` imports stay on the server. This blog works that way. Each post's MDX is compiled, and every code block is syntax-highlighted, inside a Server Component. I checked the production build: the browser chunks contain highlight.js's **CSS theme**, but **none of its JavaScript**. Readers get colored code without downloading a highlighter. **Two habits that prevent mistakes:** - Put `import "server-only"` at the top of files with secrets or database code. If a Client Component ever imports them, the build fails instead of leaking. - Pass plain data (`postId`) to Client Components, not whole objects with methods. **Honest stakes:** a Client Component in the wrong place still works. It costs bundle size and hydration time, which you feel on slow phones and big pages. Moving one `"use client"` from a page to a button is often the cheapest performance fix in an App Router project. --- ## Say it in an interview > "In the App Router, components are Server Components by default: they run only on the server, can fetch data directly, and their code never reaches the browser. `"use client"` marks a boundary: that file and everything it imports are bundled for the browser. Client Components still render on the server for the first HTML, then hydrate to become interactive. So I keep pages and data fetching on the server and put `"use client"` only on the small interactive pieces, passing them serializable props." --- ## Cheat sheet | Remember | Detail | |---|---| | Default | Server Component: runs on the server, code never shipped | | `"use client"` | Boundary: this file + its imports go to the browser | | Client Components | Still render on the server first, then hydrate | | Props across the boundary | Must be serializable: no regular functions | | `children` | Server Components can be passed into Client Components | | Where to put it | On the leaves: the button, not the page | ## TL;DR - Server Components send the result. Client Components send the result plus the code. - `"use client"` doesn't mean browser-only: Client Components render on the server too. - Everything a `"use client"` file imports ships to the browser. - Put the directive on the smallest interactive piece and pass it plain data. --- ## Why React Needs key: The Bug That Moves Your Input to the Wrong Row URL: https://bitlyst.blog/p/react-keys-reconciliation Summary: React matches list items between renders by key. Use the index and React gets the wrong match, so state ends up in the wrong row. How keys work and when an index is fine. Published: 2026-11-13 Tags: react, keys, reconciliation, lists, state Picture a shopping list with a note field on each row: ```jsx {items.map((item, i) => (
  • {item.name}
  • ))} ``` The list is Milk, Eggs, Bread. You type "2 dozen" next to Eggs. Then you delete Milk. The list now shows Eggs and Bread, and **"2 dozen" sits next to Bread.** Nothing crashed, nothing warned. The note moved to the wrong row because of `key={i}`. --- ## The mental model: name tags, not seat numbers Every render, React has to answer one question for each item in the list: **"Is this the same item as last time, or a new one?"** It answers by looking at the `key`, like checking name tags at a door. > A key is a name tag. React matches items between renders by name tag, not by position. If the tag matches, React keeps that item's state and DOM element and only updates what changed. If a tag disappears, that item is removed. If a new tag shows up, a new item is created. The index makes a bad name tag because it's really a **seat number**. When someone leaves, everyone behind them moves up a seat, and their tag changes. ![A good key stays the same wherever the item sits in the list. Photo: Travis Wise, CC BY 2.0, via Wikimedia Commons](/assets/react-keys-name-tags.jpg) --- ## How it works Comparing the new list to the old one is called **reconciliation**. Here's what React sees in the hook, with index keys: | Key | Before | After | What React concludes | |---|---|---|---| | `0` | Milk | Eggs | Same item, its name changed | | `1` | Eggs | Bread | Same item, its name changed | | `2` | Bread | (gone) | Item 2 was deleted | React thinks **Bread** was deleted and the other two were renamed. So it keeps the first two `
  • ` elements, with their inputs, and removes the last one. The input that holds "2 dozen" belonged to key `1`, and key `1` is now labeled Bread. Now the same delete with real IDs, `key={item.id}`: | Key | Before | After | What React concludes | |---|---|---|---| | `milk` | Milk | (gone) | Milk was deleted | | `eggs` | Eggs | Eggs | Same item, keep it | | `bread` | Bread | Bread | Same item, keep it | Now React removes the right row, and "2 dozen" stays with Eggs. This applies to **any state inside a list item**: text in an uncontrolled input, `useState` in a child component, focus, scroll position, a playing video, a running animation. --- ## In practice **Use a stable ID from your data:** ```jsx {items.map((item) => (
  • ...
  • ))} ``` A good key is: - **Unique among its siblings.** Two different lists can reuse the same keys. - **Stable.** The same item gets the same key on every render. Two keys to avoid: ```jsx
  • // breaks when items are removed, inserted or reordered
  • // a new name tag every render: every row is recreated ``` `Math.random()` is worse than the index. Every render, React sees all new tags, so it throws away every row and builds it again. Inputs lose what you typed and lose focus while you type. **When the index is fine:** the list never changes order, nothing is inserted or removed in the middle, and the items hold no state. A static list of footer links is fine with an index. If you leave `key` out, React uses the index for you and logs a warning. ### Bonus: a key change resets state on purpose Because a new key means "new item", you can use it to reset a component: ```jsx ``` When `userId` changes, React throws away the old form, with all its half-typed state, and mounts a fresh one. That's simpler than an effect that clears each field by hand. **Honest stakes:** with read-only lists you'll never see this bug. You'll hit it the first time a list item holds state (an input, a toggle, an expanded panel) and the list can be filtered, sorted or edited. That's most real apps. --- ## Say it in an interview > "When a list re-renders, React matches old and new items by their key to decide which ones to keep, update, add or remove. That's part of reconciliation. If you use the index as the key, removing or reordering items shifts the keys, so React keeps the wrong elements and state ends up on the wrong item. Keys should be stable and unique among siblings, usually an ID from the data. Changing a key also forces React to remount a component, which is a clean way to reset its state." --- ## Cheat sheet | Remember | Detail | |---|---| | What a key does | Tells React which item is which between renders | | Same key | Keep state and DOM, update props | | New or missing key | Mount a new item / remove the old one | | Good key | Stable, unique among siblings: `item.id` | | Index as key | Only for static lists with no state | | `Math.random()` | Never: every row is recreated each render | ## TL;DR - React matches list items by key, like checking name tags. - The index is a seat number: it shifts when items move, so state lands on the wrong row. - Use a stable ID from your data. - Change a component's key to reset its state on purpose. --- ## How V8 Makes JavaScript Fast: Ignition, Sparkplug, Maglev and TurboFan URL: https://bitlyst.blog/p/v8-compiler-tiers Summary: V8 translates your code in four stages and spends more effort only on code that runs a lot. Why the same function got 43× faster without changing a line. Published: 2026-11-13 Tags: javascript, v8, performance, jit, compilers Here's one small function, run on Node 26 with the same input every time: ```js function dist(p) { return Math.sqrt(p.x * p.x + p.y * p.y); } ``` Then the same function again, but with V8 stopped at a different stage each time: ``` Ignition only: 50.9 ns per call + Sparkplug: 31.9 ns + Maglev: 1.65 ns + TurboFan: 1.19 ns ← 43× faster than the first line ``` The code never changed. The only thing that changed is **how hard V8 worked on translating it.** --- ## The mental model: a translator who works harder on popular pages Picture a translator handed a book in a language your computer doesn't speak. - For a page read **once**, they translate it out loud on the spot, line by line. - For a page read **a few times**, they write down a quick word-for-word draft. - For a page read **hundreds of times**, they write a proper translation. - For the page everyone reads **all day**, they polish it, assuming the page always looks the way it has so far. > V8 translates your JavaScript in stages, and only spends extra effort on code that runs a lot. Each stage is called a **tier**, and the whole approach is **JIT** (just-in-time) compilation: the machine code is made while the program runs, not before. ![Interpreting on the spot is quick to start but slow per line, like Ignition. Photo: Blossom Ozurumba, CC BY-SA 4.0, via Wikimedia Commons](/assets/v8-tiers-interpreters.jpg) --- ## How it works V8 has four tiers. Each one makes faster code, but takes longer to make it: | Tier | Translator analogy | What it does | |---|---|---| | **Ignition** | reading out loud | Interprets *bytecode*, a compact list of simple instructions made from your source | | **Sparkplug** | word-for-word draft | Turns bytecode straight into machine code, with almost no thinking | | **Maglev** | proper translation | A fast optimizing compiler that uses the types it has seen so far | | **TurboFan** | polished translation | The slow, heavy optimizer for the hottest code | **Every function starts in Ignition.** While it runs, V8 counts how often it's called and records what it sees: "`p` always has `x` and `y`, and they're always numbers." That record is called **type feedback**. When a function gets **hot** (runs a lot), V8 moves it up a tier. For `dist` above, V8's own trace showed: - **Maglev** after about **500 calls**, taking 0.08 ms to compile. - **TurboFan** after about **16,900 calls**, taking 0.61 ms to compile. That's about 8× more compile time for code about 1.4× faster. That trade is why the tiers exist. Most code runs once, at startup. Spending TurboFan's effort on all of it would make every page load slower and save nothing. ### The catch: optimized code is a bet Maglev and TurboFan are fast because they **assume** the future looks like the past. "Every `p.x` has been a number, so skip the type check and do raw number math." If that assumption breaks, the fast code is wrong. So V8 throws it away and goes back to a lower tier. This is called **deoptimization**. Here, a single call with a string inside was enough: ```js dist({ x: "3", y: 4 }); // V8 drops both Maglev and TurboFan code for dist ``` The function still works, it just runs slower until V8 learns the new types and optimizes again. --- ## In practice **You can't pick a tier, and you don't need to.** V8 decides. But two habits follow from the model: **1. Keep hot code predictable.** Pass the same kinds of values to a hot function: same object shapes, numbers staying numbers. That keeps the bet safe. (For why object shape matters, see [hidden classes](/p/v8-hidden-classes-inline-cache).) ```js // before: one function, many types: harder to optimize format(42); format("42"); format(null); // after: one type per hot function formatNumber(42); ``` **2. Warm up before you measure.** The first few hundred calls of any benchmark measure Ignition, not your code at its best. Run the code many times, *then* time it. Every number in this post was taken after a warm-up. **Honest stakes:** for most app code (click handlers, a React render, a fetch), the tiers just work and none of this is worth thinking about. It matters in **hot loops**: parsers, data processing, animation, game logic. Even there, profile first. A function that never gets hot never reaches TurboFan anyway. --- ## Say it in an interview > "V8 is a JIT engine with tiers. Everything starts in Ignition, an interpreter that runs bytecode and records type feedback. Code that runs often gets compiled by Sparkplug, then optimized by Maglev and finally TurboFan, which make fast machine code based on the types seen so far. If those types change, V8 deoptimizes and falls back to a lower tier. So JavaScript is both interpreted and compiled, and keeping hot code type-stable lets it stay in the fast tiers." --- ## Cheat sheet | Remember | Detail | |---|---| | Ignition | Interpreter. Every function starts here | | Sparkplug | Quick, non-optimizing machine code | | Maglev | Fast optimizer, uses type feedback | | TurboFan | Slow, strongest optimizer, for the hottest code | | Deoptimization | Types change → optimized code thrown away | | Measured here | Same function: 50.9 ns → 1.19 ns per call (43×) | ## TL;DR - V8 translates JavaScript in four tiers, spending more effort only on hot code. - Optimized code is a bet that types stay the same. A surprise type cancels it. - The same function ran 43× faster in TurboFan than in Ignition alone. - Keep hot functions type-stable, warm up before benchmarking, and profile before optimizing. --- ## Next.js use cache, cacheLife and cacheTag: How One View Counter Rebuilt Every Page URL: https://bitlyst.blog/p/nextjs-use-cache-cachelife-cachetag Summary: use cache stores a result, cacheLife decides when it goes stale, cacheTag lets you throw it out on demand. When to use each, and where TanStack Query fits. Published: 2026-11-11 Tags: nextjs, app-router, caching, use-cache, tanstack-query Vercel's usage page told me this blog had used **2 h 32 min of function CPU** in 30 days: 80% of everything on my account. It's a blog. The posts only change when I deploy. The cause was one line near the top of my pages: ```tsx const stats = await getPostStats(); // read + comment counts, cached for 5 minutes ``` The counts were cached for 5 minutes. But the 5-minute timer didn't stay on the counts. Every page that showed them took it on, so every post, tag and series page went stale every 5 minutes and was rebuilt on the server the next time a reader or a crawler came by. --- ## The mental model: a shared fridge Think of the server cache as **one fridge that every visitor shares**. - **`"use cache"`** puts a result in the fridge. The next caller takes it out instead of cooking it again. - **`cacheLife`** is the best-before sticker. After that date, the next visitor still gets the old dish while a fresh one cooks in the background. - **`cacheTag`** is the name on the lid. You can throw out every box labelled `comments` at once, the moment the comments change. > A page is only as fresh as the shortest best-before date inside it. --- ## How it works ### `"use cache"`: store the result ```tsx async function getPost(slug: string) { "use cache"; return db.post.findUnique({ where: { slug } }); } ``` The arguments are part of the key, so `getPost("a")` and `getPost("b")` are separate boxes in the fridge. You can put `"use cache"` on a component too, and its rendered output is stored. One rule: you can't read `cookies()` or `headers()` inside. Read them outside and pass the value in as an argument. ### `cacheLife`: when it goes stale ```tsx async function getExchangeRates() { "use cache"; cacheLife("hours"); // or "minutes", "days", "max", or your own profile return fetch("https://api.example.com/rates").then((r) => r.json()); } ``` After the time is up, the next request still gets the old result straight away, and Next.js refreshes it in the background. Nobody waits. **The trap from my hook:** a page's prerendered HTML is a cached thing too. If something inside it has a 5-minute life, the whole page gets a 5-minute life. That's how one counter set the clock for every page. ### `cacheTag`: throw it out on demand ```tsx async function getComments(slug: string) { "use cache"; cacheLife("max"); // no timer... cacheTag("comments", `comments:${slug}`); // ...just a name return db.comment.findMany({ where: { slug, approved: true } }); } // when a comment is approved: revalidateTag("comments", "max"); // route handler: serve old, refresh in background updateTag(`comments:${slug}`); // server action: the next request waits for fresh data ``` A timer is a guess about when data changes. A tag means you **refresh exactly when it changes**. My comment list used to sit on the 5-minute timer. Now it's `"max"` plus a tag, and new comments still show up straight away. --- ## Which one to use | Your data | Use | |---|---| | Changes only when you deploy (posts, docs) | Nothing. It's static already | | Changes when *you* change it (CMS, comments, products) | `"use cache"` + `cacheLife("max")` + `cacheTag`, invalidate on write | | Changes on its own, slowly (rates, star counts) | `"use cache"` + `cacheLife("hours")` | | Changes constantly and shows on every page (view counts) | A small cached API route, fetched in the browser | | Belongs to one user (cart, dashboard) | Not the shared fridge. Fetch it per user | --- ## Where TanStack Query fits They solve different problems, so you use both: - **Server cache (`use cache`)** answers: *"Don't hit the database for every visitor."* One fridge, shared by everyone. - **TanStack Query** answers: *"Don't refetch for this visitor every time a component mounts."* It's each visitor's own lunchbox in browser memory, with refetch on focus, polling, retries and optimistic updates. The pattern I ended up with: render the page from server-cached data, and load live or per-user bits in the browser from a route handler that is itself cached. ```tsx // app/api/stats/route.ts — one shared, cached answer export async function GET() { return Response.json(await getPostStats()); // getPostStats uses "use cache" } // in the browser — one request per visitor, shared by every component const { data } = useQuery({ queryKey: ["stats"], queryFn: () => fetch("/api/stats").then((r) => r.json()), staleTime: 30 * 60_000, // match the server's refresh time }); ``` When the user changes something, clear both layers: `updateTag` in the server action, then `queryClient.invalidateQueries({ queryKey: [...] })` in the browser. **Honest stakes:** after moving the counts into the browser, the build output for my post, tag and series pages went from **refresh every 5m** to **refresh every 1d**. Only `/api/stats` still refreshes on a timer. Most apps won't hit this exact bug, but any value read high up in a page can quietly set the clock for the whole page. --- ## Say it in an interview > "`use cache` marks a function or component whose result Next.js stores and reuses, keyed by its arguments. `cacheLife` sets how long it stays fresh and when it's refreshed in the background, and a page can't stay cached longer than the shortest life inside it. `cacheTag` names entries so I can invalidate them when the data changes, with `revalidateTag` or `updateTag`. TanStack Query is a separate, per-user cache in the browser: I use the server cache for shared data and TanStack Query for live or per-user data." --- ## Cheat sheet | Tool | One line | |---|---| | `"use cache"` | Store this result; arguments are the key | | `cacheLife` | Best-before: stale → refresh in the background | | `cacheTag` + `revalidateTag` | Throw out by name, serve old while refreshing | | `cacheTag` + `updateTag` | Throw out by name, next request waits (server actions only) | | TanStack Query | Per-visitor browser cache on top | ## TL;DR - `"use cache"` stores, `cacheLife` sets when it goes stale, `cacheTag` lets you clear it on demand. - A page is only as fresh as the shortest-lived cache inside it. One 5-minute counter made all my pages refresh every 5 minutes. - Prefer "cache forever + tag" for data you control, timers for data you don't. - Use TanStack Query for per-user and live data, ideally fetching from a cached route. --- ## Packed vs Holey Arrays in V8: Why new Array(n) Makes Spread 4x Slower URL: https://bitlyst.blog/p/v8-packed-vs-holey-arrays Summary: V8 labels every array by what it holds and whether it may have gaps. Labels only get more general, and holey arrays take slower paths. Published: 2026-11-11 Tags: javascript, v8, performance, arrays, elements-kinds Two arrays. Same million numbers, in the same order, with no gaps in either: ```js const a = []; for (let i = 0; i < 1_000_000; i++) a.push(i); const b = new Array(1_000_000); for (let i = 0; i < 1_000_000; i++) b[i] = i; ``` Copy each one with spread: ``` [...a]: 0.17 ms [...b]: 0.71 ms ``` Same contents, same length, and `b` takes four times as long to copy. The difference is how `b` started, not what it holds. --- ## The mental model: a label in permanent marker V8 puts a label on every array's storage box. The label says two things: - **What's inside:** small whole numbers, any numbers, or anything at all. - **Whether there may be gaps:** *packed* (no gaps) or *holey* (maybe gaps). V8 reads the label to pick its fastest code. And the label is written in **permanent marker**: it can become more general, but it never goes back, even after you fix the contents. > The label describes the array's history, not its contents. V8 calls these labels **elements kinds**. --- ## How it works There are three content labels, from most specific to most general: | Label | Holds | Example | |---|---|---| | `SMI` | small whole numbers | `[1, 2, 3]` | | `DOUBLE` | any numbers | `[1, 2, 3.5]` | | `ELEMENTS` | anything | `[1, 2, "3"]` | Each one comes in a packed and a holey version, so a plain array has one of six labels. You can read part of the label with `node --allow-natives-syntax`: ```js %HasHoleyElements([1, 2, 3]); // false %HasHoleyElements(new Array(3)); // true ← born with 3 empty slots ``` `new Array(1_000_000)` doesn't create a million `undefined`s. It creates a million **holes**: slots that don't exist yet. Filling them in doesn't change the label, because V8 won't scan a million slots to check that every gap is gone. **Why gaps cost time:** reading a hole means "look further up, on `Array.prototype`". So on a holey array, V8 has to be ready for a hole at every slot. A packed array can be copied in one go. A holey one takes a slower path that handles slot by slot, and that's the 4× in the hook. These moves change the label for good: - **Holey:** start with `new Array(n)` or `[1, , 3]`, `delete arr[i]`, or write past the end (`arr[arr.length + 5] = x`). - **DOUBLE:** add one decimal, `NaN` or `-0`. - **ELEMENTS:** add one string, object, `null` or `undefined`. ```js const c = [1, 2, 3]; c.push(4.5); c.pop(); // only whole numbers again… // …but the label still says DOUBLE ``` --- ## In practice Build arrays so they're packed from the first write: ```js // before: born holey, stays holey const ids = new Array(rows.length); for (let i = 0; i < rows.length; i++) ids[i] = rows[i].id; // after: packed const ids = rows.map((r) => r.id); ``` `push`, `map`, `filter` and `Array.from({ length: n }, fn)` all give packed arrays. Three more habits: - **Fill front to back.** Writing into `[]` from the last index down made building a million-item array 6.6× slower here (38.5 ms vs 5.8 ms). - **Don't `delete` array items.** Use `splice`, or `filter` into a new array. - **Keep number arrays numeric.** One `null` placeholder moves the whole array to `ELEMENTS`. **Honest stakes:** the hook costs about half a millisecond per million-item copy. A plain `for` loop over a holey array was about 1.4× slower. Most apps will never notice. Big arrays in hot paths will: data grids, charts, parsers, game loops. Profile first. When it is the problem, the fix is usually one line where the array is created. --- ## Say it in an interview > "V8 tracks an elements kind for every array: whether it holds small integers, doubles or anything, and whether it's packed or may have holes. Optimized code and built-ins like spread pick fast paths from that kind. Transitions only go one way, toward more general, so `new Array(n)` stays holey even after you fill every slot. To keep arrays fast, build them with `push`, `map` or `Array.from`, avoid `delete`, and don't mix types into number arrays." --- ## Cheat sheet | Remember | Detail | |---|---| | Elements kind | The label: what's inside + packed or holey | | Content labels | `SMI` → `DOUBLE` → `ELEMENTS`, one way only | | Holey makers | `new Array(n)`, `[1, , 3]`, `delete`, writing past the end | | Packed makers | `push`, `map`, `filter`, `Array.from` | | Cost seen here | Spread 4.3× slower, `for` loop 1.4× slower on holey | ## TL;DR - V8 labels every array by what it holds and whether it may have gaps. - Labels only get more general. Filling the gaps never makes an array packed again. - Spreading a million-item holey array took 0.71 ms vs 0.17 ms for a packed one. - Create arrays with `push`, `map` or `Array.from`, and profile before you rewrite anything. --- ## How 'this' Works in JavaScript: Decided by the Call, Not the Code URL: https://bitlyst.blog/p/javascript-this-explained Summary: 'this' in JavaScript depends on how a function is called, not where it's written. Four rules and one arrow-function exception cover every case. Published: 2026-11-10 Tags: javascript, this, functions, arrow-functions Same function, two calls, two different results: ```js const user = { name: "Sara", hello() { return `Hi, ${this.name}`; }, }; user.hello(); // "Hi, Sara" const hello = user.hello; hello(); // TypeError: Cannot read properties of undefined (reading 'name') ``` Nothing about the function changed. Only **how it was called**. ## The mental model > `this` is like the word **"me"**. It means whoever is speaking *right now*, not whoever wrote the sentence. A function finds out what `this` is **at the moment it's called**. For arrow functions, there's one exception: they never say "me" themselves. They **repeat the "me" of the function around them**. ## How it works: look at the call To find `this`, ignore where the function was written. Look at the line that **calls** it, and check these rules in order: | How it's called | `this` is | Example | |---|---|---| | With `new` | the new object | `new User("Sara")` | | With `call`, `apply` or `bind` | whatever you pass | `hello.call(admin)` | | As `obj.method()` | the object left of the dot | `user.hello()` → `user` | | Plain `fn()` | `undefined` | `hello()` | The last row explains the hook. `hello()` has nothing left of the dot, so `this` is `undefined`, and reading `.name` from it throws. (In old scripts without strict mode, a plain call gives the global object instead of `undefined`. Modules and classes are always strict, so `undefined` is what you'll see in modern code.) The "left of the dot" rule works with any object, even one that borrowed the method: ```js const admin = { name: "Ali", hello: user.hello }; admin.hello(); // "Hi, Ali" ``` ## Arrow functions: no "me" of their own An arrow function doesn't get its own `this`. It uses the `this` of the code around it, the place where it was **written**. ```js const timer = { name: "Timer", start() { setTimeout(() => console.log(this.name)); // "Timer" }, }; timer.start(); ``` The arrow sits inside `start`, and `start` was called as `timer.start()`, so the arrow's `this` is `timer`. That's also why an arrow is a bad choice for an object method: ```js const box = { name: "Box", hi: () => this.name }; box.hi(); // this is not box: an arrow ignores the dot ``` ## Is `this` part of scope? No, and that's the main source of confusion. **Variables are decided by where the code is written.** That's scope: a function can see the variables around it. **`this` is decided by the call**, so the same function can get a different `this` each time. Arrow functions are the one place where the two meet. An arrow looks up `this` the same way it looks up a variable: from the code around it. ## In practice You'll hit this mostly when you **pass a method somewhere else**: a callback, an event handler, `setTimeout(user.hello)`. The method gets called later as a plain `fn()`, and `this` is lost. Two fixes: ```js setTimeout(() => user.hello()); // call it with the dot yourself setTimeout(user.hello.bind(user)); // or lock `this` with bind ``` ## Say it in an interview > "`this` depends on how a function is called, not where it's defined. With `new` it's the new object, with `call`/`apply`/`bind` it's what you pass, with `obj.method()` it's the object before the dot, and with a plain call it's `undefined` in strict mode. Arrow functions don't have their own `this`; they use the `this` of the surrounding code." ## Cheat sheet - `this` = "me": decided **when the function is called**. - Look at the call: `new` → new object, `call`/`bind` → what you pass, `obj.fn()` → `obj`, `fn()` → `undefined`. - **Arrow functions** use the `this` of the code around them. - Scope (variables) follows where code is written. `this` follows how it's called. - Passing a method as a callback loses `this`: wrap it in an arrow or use `bind`. --- ## turbopackRustReactCompiler: Running the React Compiler in Rust Inside Next.js URL: https://bitlyst.blog/p/nextjs-rust-react-compiler Summary: The React Compiler normally runs through Babel in Node.js. Next.js can run a Rust version inside Turbopack instead. Learn what that changes and what it saves. Published: 2026-11-10 Tags: nextjs, react, react-compiler, turbopack, rust, performance This blog's `next.config.mjs` has two lines that look like they do the same thing: ```js reactCompiler: true, experimental: { turbopackRustReactCompiler: true }, ``` They don't. The first turns the React Compiler **on**. The second picks **which version** of it runs. ## The mental model > Turbopack speaks Rust. The normal React Compiler speaks JavaScript. Without the flag, every component file goes through **an interpreter**: it's handed to Node.js, compiled there, and handed back. `turbopackRustReactCompiler` hires **a native speaker** instead: a Rust version of the compiler that runs inside Turbopack itself. Same work, same output. Just no interpreter in the middle. ## First: what the React Compiler does The **React Compiler** is a build step that adds memoization to your components for you. Memoization means "remember the last result and reuse it if the inputs didn't change". It's what `useMemo`, `useCallback` and `memo` do by hand ([quick refresher here](/p/react-memo-usememo-usecallback)). ```jsx // You write this: function Price({ amount }) { const label = formatMoney(amount); return {label}; } // The compiler outputs a version that skips formatMoney // and reuses the same when amount hasn't changed. ``` It works at build time, on every file that has components or hooks. So **how fast it runs adds to every build and every file save.** ## How it works ### Without the flag: the Babel version The official React Compiler is a **Babel plugin**, written in JavaScript. Turbopack is written in Rust, and Rust can't run JavaScript by itself. So for each file that needs compiling: 1. Turbopack sends the file's code to a Node.js process. 2. Babel reads it, runs the React Compiler, and writes out new code. 3. The new code goes back to Turbopack, which carries on bundling. That's a trip between two worlds for every component file. You also need `babel-plugin-react-compiler` installed. ### With the flag: the Rust version `turbopackRustReactCompiler` swaps in a **Rust version** of the React Compiler that runs inside Turbopack's own process. The code never leaves Rust: no handoff to Node.js and no extra package to install. ## What it saved on this blog I timed the compile step of a cold `next build` on this blog (3 runs each, on my Mac): ```text React Compiler off → 2.1 s Babel React Compiler → 2.8 s (about a third slower) Rust React Compiler → 2.1 s ← same as having it off ``` So the Rust version gave me the compiler's benefits for **no measurable build cost**, while the Babel version added about 0.7 seconds. ## In practice Turn it on if all three are true: - You use **Turbopack**, the default in Next.js 16. With `--webpack` this option throws an error. - You already have `reactCompiler: true`. The flag alone does nothing. - You're fine with **experimental**. It arrived in Next.js 16.3 to gather feedback before becoming the default. Then remove `babel-plugin-react-compiler` from your dependencies. It's no longer used. Be honest about the stakes: 0.7 seconds on a small blog is nothing. The saving grows with the number of component files, so you notice it in big apps and in dev, where every save recompiles. ## Say it in an interview > "The React Compiler automatically memoizes React components at build time. Normally it runs as a Babel plugin, so a Rust bundler like Turbopack has to send each file to Node.js and back. Next.js's `turbopackRustReactCompiler` flag uses a Rust version of the compiler that runs natively inside Turbopack, which removes that round trip. It needs `reactCompiler: true`, works only with Turbopack, and is experimental." ## Cheat sheet - `reactCompiler: true` turns the compiler **on**. - `turbopackRustReactCompiler: true` picks the **Rust** version instead of Babel. - **Babel version:** JavaScript, runs in Node.js, every file makes a round trip. - **Rust version:** runs inside Turbopack, no round trip, no Babel plugin needed. - **Limits:** Turbopack only, experimental since Next.js 16.3. --- ## What Is Turbopack? How Next.js's Rust Bundler Avoids Doing Work Twice URL: https://bitlyst.blog/p/turbopack-explained-nextjs Summary: Turbopack is the Rust bundler inside Next.js. Learn the one idea behind its speed, remembering every small step, and when you'll actually feel it. Published: 2026-11-10 Tags: nextjs, turbopack, bundler, rust, performance I built this blog twice in a row. The first `next build` compiled in **2.8 seconds**. The second, with no code changes, compiled in **0.45 seconds**. Same code, same machine. The difference is the whole idea behind Turbopack. ## The mental model > Turbopack is **a chef who never chops the same onion twice**. Every small prep step is labeled and kept in the fridge. When you change one recipe, the chef redoes only the steps that used the changed ingredient and reuses everything else. A **bundler** is the tool that turns your source files (TypeScript, JSX, CSS) into the files the browser and server actually run. Turbopack is the bundler built into Next.js, written in Rust, and it's the default since Next.js 16. (If you're unsure what a bundler does next to npm or Bun, see [who does what in a JavaScript kitchen](/p/bun-vs-npm-yarn-vite-webpack).) ## How it works ### 1. It breaks the work into tiny labeled steps Bundling is many small jobs: read a file, parse it, compile its JSX, find its imports, build a chunk. Turbopack runs each job as a small function and **remembers its result**, plus what that result depended on. ### 2. A change only redoes what depends on it When you save `Button.tsx`, Turbopack knows which steps read that file. Those steps run again. Steps for the other 500 files are reused from the fridge. That's called **incremental computation**: doing only the work that changed. ### 3. The fridge survives restarts Those results are saved to disk in `.next/cache`. Close your laptop, run `next dev` tomorrow, and most of the prep is already done. That's why my second build compiled 6× faster. ### 4. It only cooks what's ordered In development, Turbopack compiles only the pages you open. A 200-page app doesn't compile 200 pages before you see the first one. ### 5. One kitchen for server and browser Next.js builds code for the server and for the browser. webpack ran separate compilers and stitched their output together. Turbopack keeps **one graph** (a map of which file imports which) for both, so it knows exactly what changed on each side. ## Turbopack vs webpack vs Vite | | webpack | Vite | Turbopack | |---|---|---|---| | Written in | JavaScript | JavaScript (plus native helpers) | Rust | | In development | Bundles everything up front | Serves files almost unbundled | Bundles, but only what changed and what you opened | | Remembers past work | Partly | Partly | Every small step, saved to disk | | Where you use it | Anywhere | Anywhere | Next.js | The Vite row is a real design choice. Serving files unbundled is fast for small apps, but a big app can mean thousands of browser requests. Turbopack bundles in dev too, but cheaply, because almost every step is a cache hit. ## In practice You're probably using it already: `next dev` and `next build` use Turbopack by default. To compare, add `--webpack`. Be honest about the stakes. On this blog, the full build took about 11 seconds just to generate 243 static pages, cold or warm. **Turbopack speeds up compiling, not your data fetching or prerendering.** You feel it most in big apps, on dev server restarts, and when you save a file and wait for the page to update. Two things it doesn't do: - **It doesn't check types.** It removes TypeScript types without reading them. Your editor and `next build` do the checking. - **It doesn't run webpack plugins.** Most webpack loaders work, but a project that depends on a custom webpack plugin has to stay on `--webpack` for now. ## Say it in an interview > "Turbopack is the Rust bundler built into Next.js. Its main idea is incremental computation: it splits bundling into small functions, caches each result with what it depended on, and when a file changes it reruns only the affected steps. The cache is saved to disk, it compiles only the pages you request in dev, and it keeps one module graph for server and client code." ## Cheat sheet - **What:** the default bundler in Next.js 16, written in Rust. - **Core idea:** remember every small step, redo only what a change touches. - **Cache:** saved in `.next/cache`, survives restarts. - **Dev:** compiles only the pages you open. - **Doesn't:** type-check, or run webpack plugins (use `--webpack` if you need them). --- ## Bun vs npm, Yarn, Vite and Webpack: Who Does What in a JavaScript Kitchen URL: https://bitlyst.blog/p/bun-vs-npm-yarn-vite-webpack Summary: npm and Yarn fetch packages, Vite and webpack bundle code, Node runs it. Bun tries to do all of it. Learn which tool does which job. Published: 2026-11-10 Tags: bun, npm, yarn, vite, webpack, tooling Picture a job ad that says "Vite, webpack, npm, Yarn or Bun". It reads like five options for one job. **It's actually three different jobs**, and only one tool on that list tries to do all three. ## The mental model > A JavaScript project is a **kitchen**. **Node** is the stove that cooks (runs your code). **npm and Yarn** are grocery delivery (they bring packages into the pantry, `node_modules`). **webpack and Vite** are the chef who plates the food for guests (they bundle your code for the browser). **Bun** is a kitchen-in-a-box: stove, delivery and chef in one tool. Keep those three jobs in mind and every tool falls into place. ## Job 1: the stove (runtime) A **runtime** is the program that runs JavaScript outside the browser. For years that meant **Node.js**. When you type `node server.js`, Node runs it. Bun is a runtime too: `bun server.js` does the same job. It's built from different parts (Zig and Apple's JavaScriptCore engine, while Node uses C++ and Google's V8), and it can run TypeScript files directly without a separate build step. ## Job 2: grocery delivery (package manager) A **package manager** reads `package.json`, downloads the packages it lists, and puts them in `node_modules`. It also writes a **lockfile**, a receipt of the exact versions it picked, so every machine gets the same ones. - **npm** ships with Node. It's the default. - **Yarn** was created in 2016 by Facebook and others, when npm was slow and had no lockfile. npm caught up later, so today the gap is small. - **pnpm** is another option. It saves disk space by storing each package once and linking to it. - **`bun install`** does the same job and works with the same `package.json`, much faster. How much faster? I ran a quick test on my Mac: one project with React, Next.js, Vite, webpack, TypeScript and ESLint, cache already warm, `node_modules` deleted before each run. ```bash npm install # ~2.2 s yarn install # ~1.15 s (Yarn 1) bun install # ~0.2 s ← about 10× faster than npm ``` ## Job 3: the chef (bundler) Browsers don't want your 300 source files, JSX and TypeScript. A **bundler** turns them into a few optimized files the browser can load. - **webpack** is the veteran (2012). It bundles everything, even during development, and can be configured to do almost anything. That power is also why its config files get long, and why big projects start slowly in dev. - **Vite** (2020) takes a shortcut in development: it serves your files to the browser almost as they are and only transforms the file you just changed. That's why the dev server starts in about a second. For production, it still runs a real bundler. - **Turbopack** is Next.js's own bundler, now the default there ([how it works](/p/turbopack-explained-nextjs)). - **`bun build`** is Bun's bundler. So **Vite vs webpack** is a fair comparison: both are chefs. **Vite vs npm** isn't: one cooks, the other shops. ## The whole kitchen in one table | Tool | Runtime (stove) | Package manager (delivery) | Bundler (chef) | Test runner | |------|:---:|:---:|:---:|:---:| | Node + npm | Node | npm | — | `node --test` | | Yarn | — | ✓ | — | — | | webpack | — | — | ✓ | — | | Vite | — | — | ✓ | — (Vitest is separate) | | Bun | ✓ | ✓ | ✓ | `bun test` | ## In practice You don't have to switch everything at once. The easiest step is the most popular one: **keep Node and your bundler, and use `bun install` only as a faster package manager.** It reads the same `package.json`, so trying it is cheap: delete `node_modules`, run `bun install`, and see if your app still starts. Be honest about the stakes. On a small project, 2 seconds vs 0.2 seconds barely matters on your laptop. It matters in CI, where installs run on every push, and in big monorepos. Running Bun as your production runtime is a bigger step. Most npm packages work, but Node has more years in production, so test your exact stack before you commit. ## Say it in an interview > "These tools do different jobs. Node is a runtime that runs JavaScript. npm and Yarn are package managers that install dependencies. webpack and Vite are bundlers that prepare code for the browser, and Vite is faster in dev because it serves files without bundling them first. Bun is an all-in-one toolkit: a runtime, package manager, bundler and test runner, with a very fast `bun install`." ## Cheat sheet - **Three jobs:** run code (runtime), install packages (package manager), prepare code for the browser (bundler). - **Node** = stove. **npm / Yarn / pnpm** = delivery. **webpack / Vite / Turbopack** = chef. - **Bun** = kitchen-in-a-box: all three plus a test runner. - **Vite vs webpack:** Vite skips bundling in dev, so it starts faster. - **Easiest win:** use `bun install` as a drop-in faster package manager. --- ## How SSR Works in React and Next.js: Built on the Server, Wired Up in the Browser URL: https://bitlyst.blog/p/how-ssr-works-react-nextjs Summary: Server-side rendering in one picture: the server sends finished HTML, then hydration makes it interactive. Learn the steps, the gap between them, and why mismatches happen. Published: 2026-11-10 Tags: nextjs, react, ssr, hydration, rendering Open a Next.js page on a slow phone. The page shows up almost at once: text, images, a "Like" button. You tap the button and nothing happens. A second later you tap again and it works. Nothing was broken. You tapped during the gap between the two halves of server-side rendering. --- ## The mental model: a house delivered with the power off > **SSR delivers a fully built house with the electricity off. Hydration is the electrician walking through and connecting every switch to the wiring that's already there.** The server builds the page as HTML, so you see it right away. But HTML can't run code, so nothing responds yet. Then the JavaScript arrives, and React connects your event handlers to the HTML that's already on screen. Only then does the house have power. --- ## How it works, step by step **1. The server builds the house.** React calls your components on the server and turns the result into an HTML string. Here's a counter I rendered with React 19's `renderToString`: ```jsx function Counter() { const [n] = useState(0); return ; } ``` ```html ``` The text is there. The `onClick` is not. **HTML can describe a button but can't hold a function**, so all behavior is left behind. (The `` comments mark where the text pieces split, so React can find them again later.) **2. The browser shows it immediately.** No JavaScript needed to see the page. That's the main win: fast first paint, and search engines get real content instead of an empty `
    `. **3. The JavaScript arrives.** The browser downloads the same components, compiled for the client. **4. Hydration: the electrician walks through.** React runs your components again in the browser. Instead of building new DOM, it walks the HTML that's already there, checks it matches what it would have built, and attaches the event handlers. Now the button works. --- ## In practice **Next.js does this for every page by default.** No setting to turn on. In the App Router, Server Components render only on the server, and Client Components are rendered on the server *and* hydrated in the browser. That last part trips people up: **`"use client"` doesn't mean "rendered only in the browser."** It means "this also ships JavaScript and gets hydrated." The HTML for it still comes from the server. **Hydration mismatches come from the electrician finding a different house.** If the server's HTML and the browser's first render differ, React reports an error and rebuilds that part. Common causes: ```jsx

    {new Date().toLocaleTimeString()}

    // server time ≠ browser time

    {Math.random()}

    // different number each side

    {typeof window !== "undefined" ? "client" : "server"}

    // different branch ``` The fix: render the same thing on both sides first, then change it in `useEffect` or an event. Updates after hydration are fine (see [Why setState doesn't cause hydration errors](/p/react-setstate-hydration)). **The honest stakes.** On a fast laptop the gap between "visible" and "interactive" is too short to notice. On a cheap phone with a big bundle it can be seconds. Shipping less client JavaScript (fewer, smaller Client Components) shortens it more than anything else. --- ## Say it in an interview > "With SSR, the server runs the React components and sends finished HTML, so the user sees content before any JavaScript loads. Then the JS bundle downloads and React hydrates: it renders the same tree in the browser, matches it against the existing DOM, and attaches event handlers instead of rebuilding the page. If the server and client output differ, you get a hydration mismatch. Next.js does SSR for every page by default." --- ## Cheat sheet | | Who builds the HTML | User sees content | Interactive | |---|---|---|---| | **CSR** (client-side rendering) | Browser, after JS loads | Late | When content appears | | **SSR** | Server, on each request | Early | After hydration | | **SSG** (static generation) | Server, at build time | Earliest (from cache/CDN) | After hydration | - SSR = **HTML first, behavior later.** Hydration attaches the behavior. - Hydration **reuses** the server's DOM; it doesn't rebuild it. - **Mismatch** = server and first client render differ. Keep the first render the same on both sides. - `"use client"` components are still server-rendered, then hydrated. --- ## JavaScript Classes Are Functions in a Costume (and What this.constructor Points To) URL: https://bitlyst.blog/p/javascript-classes-are-functions Summary: A JavaScript class is a function with stricter rules. Learn the three rules it adds and why this.constructor lets an object reach its own class. Published: 2026-11-10 Tags: javascript, classes, this, prototypes, oop Ask JavaScript what a class is: ```js class User {} typeof User; // "function" ← surprise ``` Not `"class"`. A function. Six years ago I wrote two short posts about this, one on what a class really is and one on a `this` trick inside classes. This post folds both into one idea. ## The mental model > A JavaScript class is **a function wearing a costume**. Underneath it's the same constructor function JavaScript always had. The costume adds a few strict rules and nicer syntax. Other languages build classes into the core of the language. JavaScript added the `class` keyword in ES2015 on top of what it already had: functions and prototypes. ## What's under the costume When you write a class, JavaScript builds a function. Calling it with `new` does what constructor functions always did: 1. Create an empty object. 2. Link that object to `User.prototype`, so it can use the class's methods. 3. Run the `constructor` body with `this` pointing at the new object. 4. Return the object. ```js class User { constructor(name) { this.name = name; } hello() { return `Hi, ${this.name}`; } } const u = new User("Sara"); Object.getPrototypeOf(u) === User.prototype; // true ``` The methods live once on `User.prototype`. Every user borrows them from there instead of carrying its own copy. ## The three rules the costume adds If it's a function, why not write a plain function? Because the costume changes how it behaves: | Rule | Plain function | Class | |------|----------------|-------| | Strict mode | Only if you opt in | Always on inside the class body | | Hoisting | Usable above its definition | Not usable before the line it's defined on | | Calling it | Works with or without `new` | Throws without `new` | ```js new Late(); // ReferenceError: Cannot access 'Late' before initialization class Late {} User("Sara"); // TypeError: Class constructor User cannot be invoked without 'new' ``` All three rules catch mistakes early. Forgetting `new` on an old constructor function quietly set properties on the global object. A class throws instead. ## The this.constructor trick The second old post was about this puzzle. A `static` method belongs to the class, not to its objects: ```js class User { static greet() { return "hi from User"; } } new User().greet(); // TypeError: ... greet is not a function ``` So how can the constructor call a static method without typing the class name? Through `this.constructor`: ```js class User { constructor() { console.log(this.constructor.greet()); // "hi from User" } static greet() { return "hi from User"; } } ``` Here's why it works. Every prototype has a `constructor` property that points back to the function that made it. The new object doesn't have `constructor` itself, so JavaScript looks it up on `User.prototype` and finds `User`. **`this.constructor` is the class, so `this.constructor.greet()` is just `User.greet()`.** ![AI-generated illustration. The object can't hold a static method itself, but this.constructor is the thread back to the class that does.](/assets/js-classes-this-constructor.jpg) ## In practice Picture a subclass that overrides the static method: ```js class Admin extends User { static greet() { return "hi from Admin"; } } new Admin(); // logs "hi from Admin" ``` If the constructor had hard-coded `User.greet()`, `Admin` would still print the `User` greeting. `this.constructor` picks the class that actually ran `new`, so subclasses get their own version for free. You'll see this in base classes that read static config, such as default options or a type name. Day to day, you'll mostly hit the costume rules as error messages: "cannot be invoked without 'new'" or "before initialization". Now you know where they come from. ## Say it in an interview > "A class in JavaScript is a special kind of function. `new` creates an object linked to the class's prototype and runs the constructor on it. Compared with a plain function, a class is always in strict mode, can't be used before its definition, and throws if you call it without `new`. Inside an instance, `this.constructor` points back to the class, which is how you reach static members, and in a subclass it points to the subclass." ## Cheat sheet - `typeof SomeClass === "function"`: a class is a function in a costume. - `new` creates an object, links it to `Class.prototype` and runs the constructor. - The costume adds three rules: strict mode, no use before definition, `new` required. - `static` members live on the class, not on its objects. - `this.constructor` is the class that ran `new`, so `this.constructor.someStatic()` respects subclasses. --- ## How Next.js Turns JSX and TypeScript Into Plain JavaScript URL: https://bitlyst.blog/p/how-jsx-typescript-become-javascript Summary: Browsers can't read JSX or types. See what the compiler erases, what it rewrites, and what actually reaches the browser in a Next.js app. Published: 2026-11-10 Tags: nextjs, react, jsx, typescript, swc, turbopack Paste one line of JSX into a browser console: ```js const el =

    Hi

    ; // SyntaxError: Unexpected token '<' ``` The browser has no idea what `

    ` means inside JavaScript. Neither does it understand `: string` or `type Props`. Yet every Next.js app is written in exactly that. Something sits between your editor and the browser, translating. --- ## The mental model: a translator at the door > **The browser only speaks plain JavaScript. A compiler erases your types and rewrites every JSX tag as a function call, so what reaches the browser is ordinary JS.** Types and JSX are for you and your editor. They never ship. Picture a translator who reads your file, crosses out the notes in the margins (types), and rewrites the shorthand (JSX) in full sentences (function calls). --- ## What the translator does to one component Here's a tiny TypeScript component: ```tsx type Props = { name: string }; export function Hello({ name }: Props) { return

    Hi {name}

    ; } ``` I ran it through SWC, the compiler bundled with Next.js 16.4, using the same JSX settings Next.js uses. This is the real output: ```js import { jsxs as _jsxs } from "react/jsx-runtime"; export function Hello({ name }) { return /*#__PURE__*/ _jsxs("h1", { className: "title", children: ["Hi ", name], }); } ``` Two things happened: 1. **Types were erased.** `type Props` and `: Props` are gone. Not checked, just deleted. 2. **JSX became a function call.** `

    ` turned into `_jsxs("h1", { className: "title", children: [...] })`. The tag name is the first argument; attributes and children become an object. When that function runs, it returns a plain object, nothing magic: ```js { type: "h1", props: { className: "title", children: ["Hi ", "Sara"] } } ``` That object is a **React element**: a description of what to draw. React reads these descriptions later and turns them into real DOM (or HTML on the server). --- ## Who does what in Next.js Translating one file isn't the whole job. A real app has hundreds of files importing each other, so two tools share the work: | Step | Tool | What it does | |------|------|--------------| | Compile each file | **SWC** (written in Rust) | Erases types, rewrites JSX, turns modern syntax into what your target browsers support | | Bundle | **Turbopack** (default in Next.js 16) | Follows every `import`, groups files into chunks, splits server code from client code | | Minify (production) | SWC | Shortens names, removes dead code, makes the files small | SWC replaced Babel in Next.js 12. If you add a `.babelrc`, Next.js falls back to Babel for that project, and you lose the speed. --- ## In practice: what this means for you **Types aren't checked while you develop.** SWC deletes types without reading them. So `next dev` will happily run code with type errors; only your editor complains. `next build` is where the check happens: it runs the TypeScript compiler (`tsc`) and fails the build on errors, unless you set `typescript.ignoreBuildErrors`. **`import React` is no longer needed in every file.** Before React 17, JSX compiled to `React.createElement(...)`, so `React` had to be in scope. The newer "automatic runtime" imports the helper for you (`react/jsx-runtime`), which is why that line disappeared from tutorials. **Server code doesn't ship.** Turbopack builds separate bundles for the server and the browser. Server Components and their imports stay on the server; only files under a `"use client"` boundary end up in browser chunks. (More on that in [What is 'use client'](/p/nextjs-use-client).) --- ## Say it in an interview > "Browsers only understand JavaScript, so Next.js compiles JSX and TypeScript first. SWC, a Rust compiler, strips the types without checking them and rewrites each JSX tag into a call like `jsx('h1', props)`, which returns a plain object React uses to build the UI. Turbopack then bundles the files and splits server code from client code. Type checking is a separate step that runs in `next build`." --- ## Cheat sheet - **JSX → function call.** `

    x

    ` becomes `jsx("h1", { a: "b", children: "x" })`, which returns a React element (a plain object). - **Types → deleted.** SWC erases them; `tsc` checks them only during `next build`. - **SWC compiles** each file; **Turbopack bundles** them into server and client chunks. - **Automatic runtime** (React 17+) is why you no longer write `import React` for JSX. - Nothing you write in JSX or TypeScript reaches the browser as-is. --- ## How to Give Code Review Feedback With Evidence URL: https://bitlyst.blog/p/feedback-with-evidence-not-drama Summary: How to give feedback and run review meetings with a team member using technical evidence (PRs, CI runs, incidents) instead of opinions and drama. Published: 2026-11-07 Tags: career, feedback, code-review, teamwork, best-practices > "Honestly, your last few PRs have been sloppy. You need to be more careful." Picture saying that in a one-on-one. You mean well. You've noticed a real problem, and you think being direct is the respectful thing to do. Now watch what happens on the other side of the table. Your teammate hears "sloppy" and starts building a defense. Which PRs? Sloppy how? Everyone ships bugs. The last one was rushed because the deadline moved. Within two minutes you're not talking about code anymore. You're talking about whether they're a careful person. Nobody wins that conversation. They leave hurt, you leave frustrated, and the next PR looks exactly like the last one, because neither of you ever said what was actually wrong with it. --- ## The wrong turn: feedback is about being honest The usual advice for hard feedback is "be honest" or "be direct." It sounds right. Vague, soft feedback is useless, so the cure must be saying what you really think. The trouble is that "what you really think" is usually a judgment, not a fact. "Sloppy," "not careful," "lacks ownership," "too slow." These are conclusions you reached from things you saw. When you share only the conclusion, you're asking the other person to accept your verdict without seeing the case. So they do what any engineer does with an unproven claim. They argue with it. The opposite move fails too. Picture softening it into a "feedback sandwich": a compliment, a vague "maybe a bit more care on PRs," another compliment. Your teammate leaves feeling fine and learns nothing. Three months later the problem comes up again in a performance review, and now it feels like an ambush. Both versions have the same flaw. Neither gives the other person anything concrete to look at. --- ## The reveal: feedback is a bug report about a process You already know how to describe a problem without drama. You do it every time you file a good bug report. A bad bug report says "the checkout is broken." A good one says: on this page, with these steps, I expected this, and I got that. Here's the log. Nobody gets defensive about a good bug report, because it isn't about anyone. It's about what happened. Feedback works the same way. The Center for Creative Leadership teaches this as the [Situation-Behavior-Impact model](https://www.ccl.org/articles/leading-effectively-articles/closing-the-gap-between-intent-vs-impact-sbii/): describe **when and where** it happened, the **observable behavior** (what a camera would have recorded, not what you think it means), and the **impact** it had. In engineering, the "camera" is already running. Your Git history, CI logs, review threads and incident timelines record almost everything. Here's the same message, rewritten from verdict to evidence: | Drama | Evidence | |---|---| | "Your PRs are sloppy." | "PRs #412, #418 and #425 were merged with failing lint checks. Here are the CI runs." | | "You don't care about testing." | "The payment refactor in #431 changed 600 lines and added no tests. The bug in the refund flow last Tuesday came from that change." | | "You're too slow." | "The search ticket was estimated at 3 days and closed after 9. I'd like to understand where the time went." | | "You ignore review comments." | "On #440, two comments about the N+1 query were marked resolved without a change. The query showed up in last week's slow-request log." | Read the right column again. Every line can be checked. If it's wrong, your teammate can show you, and that's a good outcome too. If it's right, there's nothing to argue about except what to do next. Notice what else changed. The evidence column describes the work. It never describes the person. > Judge the commit, not the committer. A diff can be wrong without anyone being bad. That idea isn't new. Google's SRE book describes [blameless postmortems](https://sre.google/sre-book/postmortem-culture/): after an incident, the write-up focuses on what happened and what contributed to it, not on who to blame. The book's reasoning is practical. If people expect to be shamed, they stop reporting problems, and you lose the information you need to fix things. A one-on-one is a tiny postmortem, and the same rule applies. ![Photo: Mikhail Nilov on Pexels](/assets/evidence-feedback-screen.jpg) ### Evidence has limits Evidence keeps you honest, but it doesn't tell the whole story. A ticket that took 9 days instead of 3 might mean the developer struggled. It might also mean the API docs were wrong, the designer changed the spec twice, or they spent four days helping someone else ship. That's why the evidence opens the conversation instead of closing it. You bring the facts. Then you ask what you're missing. Be careful with metrics, too. Commit counts, lines of code and number of PRs are easy to collect and easy to game, and they say almost nothing about whether the work was good. Pick evidence that points to a specific outcome (a failed deploy, a reopened bug, a slow query), not a number that only measures activity. --- ## The fix: run the meeting like a code review A good review ends with an approved diff. A good feedback meeting ends with an agreed change you can check. A few rules get you there. **Write it down first.** If you can't write the feedback as a list of links and facts, you're not ready to give it. Often you'll find that your strong feeling is backed by one PR, not a pattern. That's worth knowing before you say "always." **Send the notes ahead.** Surprise is where drama starts. If your teammate has a day to read the evidence, they arrive having thought about it instead of reacting to it. **Ask what you're missing.** Read the facts and the impact, then stop and listen. If new context comes up, like an unclear spec or a broken test setup, the fix is in the process, not the person. Update your notes. **Use the same format for praise.** "Great job this sprint" is as empty as "sloppy." Compare it with: "The caching change in #455 cut the dashboard's response time in the APM graph from about 2 seconds to under 300 ms. That's the main reason the support tickets stopped." Specific praise tells people what to keep doing, and it proves your feedback is about the work in both directions. **End with something you can check.** "Be more careful" can't be verified. "Turn on the required lint check for the repo, and we'll look at the next five PRs together" can. Put a date on it. A simple note template is enough: ```md ## Feedback notes — 2026-11-14 ### Situation Sprint 44, payment refactor (#431) ### What happened - 600 lines changed, 0 tests added - Refund bug on 2026-11-04 traced to this change (incident INC-112) ### Impact - 41 refunds failed for 3 hours - Support handled the tickets manually ### Questions for you - Was there a reason tests were skipped? (time? unclear test setup?) ### Proposed next step - Add refund-flow tests before the next payment change - Check: CI coverage report on the next payments PR ``` The numbers in that note are made up for the example. In yours, every number should come from a real log, dashboard or ticket. If you have to estimate it, say so. --- ## The takeaway If a piece of feedback would make a bad bug report, it will make a bad conversation. Bring the logs, describe what happened, ask what you missed, and agree on a change you can measure. Drama comes from verdicts. Evidence turns a verdict into a problem two engineers can solve together. ## TL;DR - Judgments like "sloppy" or "slow" start arguments because the other person has to accept your conclusion without seeing the evidence. - Use the Situation-Behavior-Impact structure: when it happened, what a camera would have recorded, and what it caused. - Engineering already records the evidence for you: PRs, CI runs, review threads, incident timelines and dashboards. - Share the evidence before the meeting, ask for context you might be missing, and give praise in the same specific format. - End every feedback conversation with one change and a way to check that it worked. --- ## How to Learn a New Technology: Start With the Docs URL: https://bitlyst.blog/p/learn-from-official-docs-first Summary: Why official technology docs should be your first step when learning, how to choose videos, books, podcasts or courses next, and how to keep up with changes. Published: 2026-11-06 Tags: learning, documentation, career, nextjs, best-practices ```ts // 31 October: I added this to my blog's homepage export const revalidate = 600; // 1 November: I deleted it and wrote this instead "use cache"; cacheLife("hours"); ``` That's real, and it's in this blog's git history. On 31 October, I added `revalidate` to pages across the site. The next day, I turned on Next.js Cache Components and removed every one of them. `revalidate` wasn't a bad line. It's a normal way to cache a Next.js page, and countless tutorials teach it. But the docs for the version I run say this about the switch I made: > After enabling the flag, route segments that still export `dynamic`, `revalidate`, or `fetchCache` will error. So the same line can be correct in one project and an error in another, depending on the version and the setup. A tutorial can't know which one you have. The docs can. --- ## The wrong turn: start with the best course you can find When you want to learn something new, the natural first step is to search for "best React course" or "learn Next.js tutorial." You pick the one with good reviews and start at lesson one. The docs feel like something for later: dry, long, and made for people who already know the subject. It seems reasonable because a good course is friendly and has a clear order. But every course, video and article is a snapshot. It shows the technology on the day it was made, and the technology keeps moving. ![Photo: Vo Thuy Tien on Pexels](/assets/learn-docs-old-tech.jpg) You can see this in React. When [the new docs launched in 2023](https://react.dev/blog/2023/03/16/introducing-react-dev), the team moved the old site to an archive and said it "will not get many more updates." The new docs "teach React with Hooks from the beginning." Class components still work, but someone starting from an older class-based tutorial would be learning a style the React team no longer teaches first. Community answers age the same way. [A study of obsolete Stack Overflow answers](https://arxiv.org/abs/1903.12282) found that 58.4% of them were probably already out of date when they were first posted. When readers noticed an obsolete answer, only 20.5% of those answers were ever updated. That study is from 2019, but the problem hasn't gone away: an answer stays online long after the technology has changed. AI has its own version of this. Next.js now adds a note for AI tools to projects like mine, warning that the APIs "may all differ from your training data," and tells them to read the docs that ship with the package. Even the AI gets told to read the docs first. I wrote more about working with AI in [this post](/p/ai-is-your-junior-developer). --- ## The reveal: docs are the only source that moves with the technology Docs are written or approved by the people building the technology, and a change in the technology is supposed to come with a change in the docs. That's the difference. Everything else about the technology is someone's report on it, from some point in time. The best part is that good docs also record what changed. Many Next.js docs pages end with a version history table. Here's part of the one for `proxy`: ``` v16.0.0 Middleware is deprecated and renamed to Proxy. Proxy defaults to the Node.js runtime v15.5.0 Middleware can now use the Node.js runtime (stable) v15.2.0 Middleware can now use the Node.js runtime (experimental) ``` Three lines tell you why an older tutorial talks about `middleware.ts`, and what the name is today. To see how fast this moves, I counted those tables in the docs bundled with Next.js 16.4.3, the version this blog runs. 112 pages have one. They list 83 entries for version 16 alone, and 54 of those came after 16.0: | Version | Entries in the docs | |---|---| | 16.0 | 29 | | 16.1 | 5 | | 16.2 | 15 | | 16.3 | 19 | | 16.4 | 15 | *Counted with `grep` on `node_modules/next/dist/docs`. Some entries describe the same change on more than one page, so this isn't an exact count of features. It's a sign of how much moves between releases.* No course could keep up with that. It doesn't need to, as long as you know where the current truth lives. > **A course teaches you how a technology worked when it was recorded. The docs tell you how it works now.** --- ## The fix: docs first, then your own way Docs first doesn't mean reading every page before you do anything. It means making the docs your starting point and your reference, then learning the rest however suits you. ### Step 1: Read the docs for a map, not for mastery Here's what to look at on the first visit: 1. **The version.** Check which version you're using and make sure the docs match it. Next.js even ships its docs inside the package, in `node_modules/next/dist/docs`, so they always match what you installed. 2. **The introduction and getting started guide.** Follow it and run the example. Now you've seen the official way to do things. 3. **The main concepts.** Read them to learn the vocabulary. Every video and book afterward will be easier because you know the words. 4. **The sidebar.** Skim the whole thing without reading every page. It's a map of what the technology can do, and you can't look something up later if you don't know it exists. You don't need to understand it all. You only need to know what's there and where to come back to. ### Step 2: Find your own way of learning ![Photo: Alex Qian on Pexels](/assets/learn-docs-books.jpg) Docs tell you what's true, but they often aren't the best teacher. They rarely explain the mistakes people make, or why one approach beats another in a real project. That's what everything else is for, and developers clearly use a mix. Here's what people reported using to learn in [Stack Overflow's 2025 survey](https://survey.stackoverflow.co/2025/developers), across all respondents: | Way of learning | Used in the past year | Good for | Watch out for | |---|---|---|---| | **Technical docs** | 67.8% | What's true right now | Rarely teaches in the best order | | **Videos** | 50% | Watching someone work | It's easy to watch and not practice | | **AI tools** | 44% | Questions about your own code | Can be out of date and sound sure | | **Blogs and podcasts** | 34.8% | Real stories, context, the "why" | One person's experience, and podcasts can't teach syntax | | **Courses** | 32.7% | A clear path with exercises | May be recorded on an older version | | **Books** | 30.4% | Deep fundamentals | Framework details age quickly | So which one should you pick? You've probably heard "I'm a visual learner" or "I learn by listening." Be careful with that idea. [A well-known 2008 review](https://pubmed.ncbi.nlm.nih.gov/26162104/) found almost no good evidence that teaching people in their preferred style improves how much they learn. That doesn't make your preference useless. It only changes the reason for choosing: - **Choose what you'll actually finish.** The best course you quit in week two teaches less than a simple book you complete. If you only have time on your commute, a podcast beats the video you never start. - **Choose what fits the subject.** Use a video to see a tool being used, a book for how databases work inside, and a podcast to hear how a team made a decision. - **Mix them.** You don't have one fixed style. Try something for a week, and change it if it isn't working. ![Photo: cottonbro on Pexels](/assets/learn-docs-podcast.jpg) Two habits matter whichever you choose. Check the date and the version before you start, and compare them with the docs. And build something small, because you only find out what you really understood when nobody is telling you the next step. ### Step 3: Keep following the docs Learning a technology doesn't end, because the technology doesn't stop changing. New features show up in the docs before most tutorials exist. Here are a few real entries from Next.js 16.4, which you can find with one command: ```bash grep -rhE '^\| *`?v?16\.4\.' node_modules/next/dist/docs ``` ``` | `v16.4.0` | `ensureStatic` introduced. | | `v16.4.0` | Add the `next analyze export` command. | | `v16.4.0` | `next-bundle-optimizer` skill added. | ``` You don't need a big system for keeping up: - **Read the release notes** for the tools you use most when a new version comes out. - **Read the upgrade guide before upgrading,** not after something breaks. - **Check the version history** on a page when an old answer doesn't match what you see. - **Reread the docs for your main tool sometimes.** Pages you read a year ago may have changed, and you'll understand more of them now. --- ## The honest stakes I can't show you a study proving that docs-first learning is faster. The survey shows docs are popular, not that they're better. This is my recommendation, based on how often these tools change, and the evidence above is about content going out of date. There are real limits, too: - **Complete beginners may feel lost.** Docs usually assume you know the basics. If you're new to programming, start with a guided course on the language, then come to the docs for each framework. - **Not all docs are good.** Small libraries may have only a thin README, and docs can have gaps and mistakes. Then the source code and the issue tracker become your docs. - **Old doesn't always mean wrong.** Fundamentals age slowly. A good book on networking or databases can stay useful for years, and `revalidate` from my opening example is still documented for projects that don't use Cache Components. The point isn't that courses and tutorials are bad. Use them, and enjoy them, but don't let them be your only source of truth. --- ## The rule Start with the docs to learn what's true, use whatever way you'll stick with to understand it, and come back to the docs to see what changed. --- ## TL;DR - Courses, videos and articles are snapshots, while official docs are meant to change along with the technology. - Use your first visit to the docs as a map: check the version, run the getting started guide, learn the main concepts and skim the sidebar. - After that, choose videos, books, podcasts or courses based on what you'll finish and what fits the subject, since there's little evidence for fixed learning styles. - Always check a resource's date and version against the docs, and build something small to test what you learned. - Keep following release notes, upgrade guides and version history, because that's where new features and changes show up first. --- ## AI Is Your Junior Developer. Your Product Still Needs a Senior. URL: https://bitlyst.blog/p/ai-is-your-junior-developer Summary: AI coding tools are assistants, not owners. Why every product needs a senior engineer to review, observe and maintain what AI builds. Published: 2026-11-06 Tags: ai, ai-coding, code-review, observability, software-engineering, best-practices ``` Add CSV export to the orders page. ``` That's the whole ticket. Picture typing it into your AI tool and going to lunch. You come back to a finished feature. The button works, the file downloads, the tests are green. You feel like you hired an extra developer for the price of a subscription. Then you open the diff. There's a new package nobody on your team has heard of. There's a new date formatter sitting next to the one you already have. The export loads every order into memory, and the route never checks whether this user is allowed to see those orders. ![Photo: nemuel on Pexels](/assets/ai-junior-diff.jpg) Nothing here looks broken in a demo. All of it is a problem in production, and none of it is really the AI's fault. Now replace "AI" with "the junior who joined on Monday." Would you give them one sentence on their first day, no docs, no design, no acceptance criteria, then disappear until they said "done"? If that went badly, whose mistake would it be? Then ask a bigger question. Once that feature is live, who watches it? Who notices it getting slower, keeps it maintained, and answers when it breaks next year? > **Every product people depend on needs a senior engineer who owns it. AI can assist with almost all of that work, but it can't be the owner.** --- ## The wrong turn: a faster developer needs less managing The tempting belief goes like this: AI writes code quickly, so my job is to ask for features and check that they work. Less typing, less thinking, more output. It feels right because the speed is real and you can see it. The problem is that the feeling isn't a reliable measuring tool. In 2025, METR ran [a randomized trial](https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/) with 16 experienced open source developers working on 246 tasks in their own repositories. Each task was randomly allowed or not allowed to use AI. They expected AI to make them 24% faster. They took 19% longer. And after doing the work, they still believed AI had made them 20% faster. That result needs an honest footnote, because it's easy to misuse. It's a small study of early-2025 tools, and METR itself marks it as out of date. [Its 2026 follow-up](https://metr.org/blog/2026-02-24-uplift-update/) points toward developers now being faster, but METR calls that data unreliable, partly because many developers refused to work on tasks without AI. So this study doesn't prove AI makes you slower. It proves something more useful: experienced developers can be wrong about their own speed by a wide margin, in the direction that feels good. The large surveys show a similar gap between how AI feels and what it delivers: | Source | What it found | |---|---| | [DORA 2025](https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report), nearly 5,000 professionals | More than 80% believe AI raised their productivity. AI adoption is linked to more throughput and also to less stable delivery. | | [Stack Overflow 2025](https://survey.stackoverflow.co/2025/ai) | 84% use or plan to use AI. 46% distrust its accuracy and 33% trust it. The top frustration, at 66%, is answers that are "almost right, but not quite." | "Almost right" is exactly how you'd describe a junior's first merge request. Developers already know how to handle that. They review it. --- ## The reveal: it is a junior, with a few dangerous differences Most of what goes wrong with AI code is familiar. It solves the ticket without knowing the codebase. It writes something new because it doesn't know the old thing exists. It handles the happy path and misses the rule nobody wrote down. Those are junior mistakes, and the research lines up with them: - **It doesn't protect your project's consistency.** GitClear looked at [211 million changed lines](https://www.gitclear.com/ai_assistant_code_quality_2025_research) from 2020 to 2024. Lines tied to refactoring fell from 25% of changes in 2021 to under 10% in 2024, while copy-pasted lines rose from 8.3% to 12.3%. That's a trend during the years AI tools spread, not proof that AI caused all of it, and GitClear sells code analytics. It still matches what you see in that CSV diff: a second date formatter. - **It doesn't think about security unless you make it.** [Veracode's 2025 test](https://www.veracode.com/press-release/ai-generated-code-poses-major-security-risks-in-nearly-half-of-all-development-tasks-veracode-research-reveals/) gave more than 100 models 80 coding tasks. They introduced a known type of vulnerability in 45% of cases, and failed to prevent cross-site scripting in 86% of the relevant cases. Veracode sells security tools and models keep changing, so treat the exact number with care. The lesson is that code can work perfectly and still be unsafe. - **It can pick a package that doesn't exist.** [A USENIX Security study](https://www.usenix.org/publications/loginonline/we-have-package-you-comprehensive-analysis-package-hallucinations-code) generated 576,000 code samples and found invented package names in [at least 5.2% of samples from commercial models and 21.7% from open source ones](https://arxiv.org/abs/2406.10279). About 45% of those invented names came back every time the same prompt was repeated. A name that repeats is a name an attacker can register and fill with malware. So far, this is only a junior with a good memory for syntax. But four differences make it riskier than the person who joined on Monday: | | Human junior | AI | |---|---|---| | **When unsure** | Often looks unsure, or asks you | Can sound equally confident when right and when wrong | | **When the brief has a gap** | May come to your desk | Often fills the gap with a guess and keeps going | | **After your review** | Remembers it next month | Forgets it, unless it's written somewhere it can read | | **Speed** | A merge request every few days | Can produce more than you can carefully read | The third row changes the job. A human junior improves because of your reviews. An AI tool improves because of your documents. If your feedback stays in a chat window, you'll give the same feedback forever. The fourth row explains the DORA result. Their summary is that [AI is an amplifier](https://dora.dev/research/2025/dora-report/), "magnifying an organization's existing strengths and weaknesses." In their words, without "strong automated testing, mature version control practices, and fast feedback loops, an increase in change volume leads to instability." More code goes into the same pipe, and if your review is weak, it now fails faster. > **AI doesn't remove the senior's work. It moves your time from typing code to directing and checking it.** --- ## The fix: run it the way you'd run a new junior Here's the same CSV feature, handled the way a good senior handles a new teammate. Every step below would have caught something in that first diff. ### Onboard it before you assign it anything A new teammate gets the architecture, the conventions, and a tour of where things live. AI needs the same, written down. Most tools read a project file for this, such as `AGENTS.md` or `CLAUDE.md`. Keep it short and make it about your project, not good practice in general: ```md ## Structure - Database access lives in lib/db. Components never query directly. - Use lib/format.ts for dates and money. Don't write new formatters. ## Dependencies - Ask before adding a package. Explain why existing code can't do the job. ## How to work - Plan first, then code. If the plan stops fitting, stop and ask. - Keep diffs small. No unrelated refactors. ## Done means - Typecheck, lint and tests all pass. ``` This idea has reached the frameworks too. When I run `next dev` on this blog, Next.js adds a note to the repo's `AGENTS.md` that speaks directly to the AI: "This version has breaking changes — APIs, conventions, and file structure may all differ from your training data." It then tells the agent to read the docs that ship with the installed package. The framework's own authors expect AI to be confidently out of date, so they onboard it. ### Give it a brief, not a wish Compare the one-liner from the start of this post with this: ```md Task: CSV export on the orders page. Read first: docs/orders.md, lib/format.ts, and the design at . Acceptance criteria: - Exports all rows matching the current filters, not only the visible page - Users without orders:read get a 403 - Uses formatDate and formatMoney from lib/format.ts - Streams the file, so a large export doesn't load everything into memory - Tests cover the filters and the 403 Out of scope: scheduled exports, Excel format. Don't write code yet. Show me your plan first. ``` Writing that takes a few minutes, and it's the same thinking you'd do for a person. Look at what it closes: the formatter, the memory problem and the permission check are now requirements instead of luck. If you can't write the acceptance criteria, you aren't ready to delegate the task, to anyone. ### Read its plan before it writes code This is the cheapest review you'll ever do. A wrong direction costs one sentence to fix at the plan stage and a whole diff to fix later. Ask it what it read and what it plans to change. Look for the things a junior wouldn't know to worry about: is it rebuilding something that exists? Is it changing a shared module for one small feature? Did it actually look at the code, or is it assuming? ### Guard the door: packages and tools A new dependency is a long-term decision that takes the AI one line to make. Treat it the way you'd treat a junior's `package.json` change: it needs a reason. Before accepting one, check that it's real and alive, because of the invented-name problem above: ```bash npm view some-package repository.url time.modified maintainers ``` The same goes for new patterns and tools. If the project uses one state library and the diff quietly adds a second, that's a review comment even if the code works. Every tool works in isolation. Consistency is the thing the AI can't see unless you hold it. ### Stay in the room This is the part I feel strongest about: you can't announce "we need feature A" and come back when it's over. You wouldn't do it with a junior, and the AI won't come to your desk when it gets lost. ![Photo: mizunokozuki on Pexels](/assets/ai-junior-review.jpg) Watch how it works, especially early on. If it's reading the wrong files, or has tried the same failing fix three times, or starts editing things outside the task, stop it. Correcting course halfway costs far less than unpicking the result. Work in slices, too. Build the export endpoint, review it, then add the button. A diff small enough to read gets a real review, and a huge one gets a skim and a thumbs up. ### Review it like a junior's merge request Green tests aren't the finish line, especially when the same author wrote the code and the tests. A test can pass because it checks the wrong thing. Read the diff, and ask what you'd ask a person: - Does it meet each acceptance criterion, and can you show where? - Does it reuse what exists, or did it add a second version? - Who is allowed to call this, and where is that checked? - What happens with empty input, huge input, or a failure halfway? - Could you explain this code if it broke at 2 AM? That last one matters most. When you merge it, it's your code. "The AI wrote it" won't mean anything in the incident review. ### Turn each repeated mistake into a rule This is where most of the long-term value is, and it's the same habit as a good mentor's: don't only fix the mistake, fix why it happened. You can see this in the history of this blog. On 31 October, `CLAUDE.md` told whoever was writing posts to use "first person." That rule had a hole in it: a made-up example could read like something that really happened. By the next day it said "first person only for real experiences," with made-up scenarios written as "picture…" and "you." It's the reason this post opens with "picture" and not with a story about a developer who doesn't exist. The same commit added a section on caching, with rules like this one: ```md Don't read the clock (new Date(), Date.now()) or Math.random() in server components outside a "use cache" scope — it fails the prerender. ``` It's specific, and it says why. That's what a useful rule looks like. When a mistake can be caught by a machine, go further than a rule. A lint rule, a type or a failing test works every time, whether or not anyone remembered to read the docs. And maintain these files like code: rules go stale when the project changes, and a stale rule will mislead the AI as confidently as a wrong comment misleads a person. --- ## Delegation is something it earns You probably do want the end state: hand over a task and get back something you'd happily merge. That's how good juniors grow too. You don't get there by deciding to trust them. You get there by watching them handle bigger jobs without surprises. | Stage | What you hand over | How you work | Move up when | |---|---|---|---| | **1. Pairing** | One function or fix | You watch and read every line | Your rules are stopping the common mistakes | | **2. Supervised** | One slice of a feature | You approve the plan, then review the diff | Plans rarely need big corrections | | **3. Trusted** | A full ticket of a familiar type | You write the brief, then review the merge request | Your reviews mostly find small things | | **4. Delegated** | A repeated type of task | It works alone, and CI and a final review guard it | You keep checking, and move it back down if quality slips | Three things about this table are easy to miss. First, trust is per type of task, not per tool. You might fully delegate writing tests for pure functions and never get past stage 2 on payment code. A good senior gives out work the same way: based on what the task can break. Second, it's slow. I can't give you an honest number for how long it takes, because it depends on your codebase and how much is already written down. But the time isn't wasted, because everything you put in stays in the repo. Better docs and stricter checks also help your human teammates. Third, there's no stage 5 where the senior leaves. Delegating a task isn't the same as giving away responsibility for the product. A good tech lead delegates nearly everything and still answers for the result. --- ## Merging is the start of the long-term problems So far, everything has happened before the merge. But a product spends its life after the merge, and that's where AI left alone does the most lasting damage. Go back to the CSV export, and picture it passing every review. A year later, the orders table is far bigger. Exports that took seconds now time out. They hold database connections for so long that unrelated pages slow down. Customers complain before anyone on the team knows. No test failed, and nobody changed that code. The AI said nothing, because nobody asked it anything. That's the gap. A coding tool works on the task in front of it. Nobody hands it the job of caring about this product next year, and it can't be held to account for what happens then. The long-term cost is starting to show up in research. [A Carnegie Mellon study](https://arxiv.org/abs/2511.04427), published at MSR 2026, compared 806 GitHub projects that adopted Cursor with 1,380 similar projects that didn't: | What they measured | Result after adopting Cursor | |---|---| | Lines of code added | 3–5x increase in the first month, with the gains gone after two months | | Static analysis warnings | Up 30%, and it lasted | | Code complexity | Up 41%, and it lasted | The authors also found that those warnings and that complexity were major factors in the later slowdown. The speed was real, and so was the bill that came after it. This is one tool, in open source projects, during early adoption up to March 2025, and teams with strong review may do far better. That's the point, though: speed without an owner turns into debt. So here's the work that needs a senior, and where AI fits into it: | Area | AI can assist by | The senior stays responsible for | |---|---|---| | **Observability** | Adding logs and traces, drafting dashboards | Deciding what must be watched and what should wake someone up | | **Performance** | Finding slow queries, writing load tests, proposing fixes | Setting targets, reviewing trends, judging the trade-offs | | **Maintenance** | Drafting dependency upgrades and migrations | Choosing what to upgrade and when, with a rollback plan | | **Incidents** | Reading logs, suggesting likely causes | Deciding to roll back, telling users, making sure it doesn't repeat | | **Architecture** | Laying out options and their costs | Choosing the one the team will live with for years | For a starting point on what to watch, Google's SRE book names [four golden signals](https://sre.google/sre-book/monitoring-distributed-systems/): "latency, traffic, errors, and saturation." On the CSV export, that's how long exports take, how many people run them, how many fail, and how close the database is to its limit. The book's reason for monitoring is the same as this post's: it lets a system "tell us when it's broken, or perhaps to tell us what's about to break." Reviewing those numbers on a schedule is a real part of the job, and connecting AI to them is a good idea. It can spot the climbing line and summarize a hundred log entries in seconds. But judgment stays with you. Ask for a fix to that timeout with no context, and one valid-looking answer is a longer timeout. A senior asks why it's slow, whether the design still fits the data, and what else this will hurt. If your team has no senior engineer, bring one in, even part-time, before real users arrive and not after the first outage. ### The honest stakes All of this has a cost, and sometimes it isn't worth paying. For a throwaway script or a weekend prototype nobody will maintain, go ahead and ask for the feature and see what comes back. The risk is small, so light supervision is fine. The junior comparison also has limits. A junior is a person whose growth is part of the point, and this tool has no career to invest in. You can also throw away an AI's attempt and start again without hurting anyone's feelings, which you should do more often than you would with a colleague. The comparison is a guide for how to supervise the work, not a claim about what the tool is. And the evidence is moving. Most of the studies here are from 2025, and models have changed since. Newer tools will likely make fewer of these mistakes. They won't know your product's unwritten rules unless someone writes them down, and they won't be accountable for what ships. --- ## "I built it with no technical knowledge, so it'll be easy for you" That weekend prototype leads to the most expensive version of this problem: the one with no senior in the loop at all. Picture a meeting. Someone from sales or product, with no engineering background, opens a laptop and shows a working app they built with AI. It has a login, a dashboard and real customer data. It's impressive, and they know it. Then comes the sentence: "I built this without any technical knowledge. You're much better at this than I am, so maintaining it will be easy for you." It sounds logical, and it's wrong. ![Photo: goumbik on Pexels](/assets/ai-junior-solo.jpg) Being easy to build says nothing about being easy to maintain. It was easy because the AI made hundreds of decisions and nobody had to look at them: how permissions work, where the secrets live, what the data model assumes, what happens when two people edit the same record. Those decisions didn't go away. Nobody has reviewed them yet. A better engineer doesn't make those problems smaller. They only see more of them. And the team isn't inheriting code from a colleague they can ask, because the author can't explain why any of it is the way it is. Every question gets the same answer: "I don't know, the AI did that." The team now owns production software with no history, no reasoning, and often no tests. Even the person who named this way of working didn't claim otherwise. When Andrej Karpathy coined "vibe coding" in 2025, [he wrote](https://simonwillison.net/2025/Mar/19/vibe-coding/) "I 'Accept All' always, I don't read the diffs anymore," and described it as "not too bad for throwaway weekend projects." The limit was in the original description. Two public cases show what's at stake once real users arrive: - **Data left open.** In 2025, researcher Matt Palmer [scanned 1,645 projects](https://mattpalmer.io/posts/statement-on-CVE-2025-48757/) from the showcase of Lovable, an AI app builder. He reports that 170 of them, about 10%, had database access rules weak enough to expose data such as names, phone numbers, API keys and payment details. These apps can look finished on the surface, which is the point. Palmer works at Replit, a competitor, so read it with that in mind, and Lovable has since added a security scan. - **Production deleted.** Also in 2025, SaaStr founder Jason Lemkin [reported](https://fortune.com/2025/07/23/ai-coding-tool-replit-wiped-database-called-it-a-catastrophic-failure/) that a Replit agent deleted their production database during a declared code freeze, wiping records for more than 1,200 executives. The account comes from Lemkin's own posts, and [the data was later recovered](https://www.theregister.com/2025/07/21/replit_saastr_vibe_coding_incident/). Replit's CEO called it unacceptable, and the company began separating development and production databases. That's a basic safeguard an experienced engineer would ask about first. None of this means non-technical people shouldn't build with AI. They should. A working prototype beats a long requirements document, because everyone can click it and argue about something real. The mistake is what happens next, so change the handover: - **Call it a prototype.** Bring it early, before it has real users or real data, and say "this shows what I want," not "this is what you'll maintain." - **Let the team choose.** Adopt, rework or rebuild is an engineering decision, made after reading the code and estimating the cost. It can't be assumed because the demo works. - **Name an owner first.** Someone has to be able to explain the code and answer the phone when it breaks at 2 AM. If nobody can, it isn't ready for production. - **Review it before real data goes in.** At minimum, check permissions, secrets, backups, separate environments, and tests for what matters most. This isn't really about job titles. A senior developer who merges every AI diff unread is in the same position as the person in that meeting, with a better vocabulary. What matters is whether anyone understands the thing they're asking others to run. --- ## The rule Give every product a senior engineer who owns it, from the first brief to production and beyond. Use AI as a fast junior: brief it, watch it, review it, write down what it got wrong, and give it more as it earns trust. Let it assist with everything, and let it own nothing. --- ## TL;DR - Every product people depend on needs a senior engineer who owns its maintenance, observability and performance, because AI can assist with that work but can't be accountable for it. - AI behaves like a very fast junior, so give it project rules, a brief and a required plan, review its diffs like a merge request, and turn repeated mistakes into rules or automated checks. - Feeling faster isn't evidence: in METR's 2025 trial, developers took 19% longer with AI and still believed it had made them 20% faster, although METR now considers that result out of date. - Unsupervised speed can become long-term debt: in a Carnegie Mellon study of Cursor adoption, the speed gains faded after two months while warnings rose 30% and code complexity 41%. - An app built without technical knowledge is a valuable prototype, not a handover, because being easy to build says nothing about being easy to maintain. --- ## V8 Garbage Collection: Why Middle-Aged Objects Are the Expensive Ones URL: https://bitlyst.blog/p/v8-garbage-collector-survivors Summary: How V8's generational garbage collector works: scavenges cost per survivor, short-lived objects are nearly free, and pretenuring makes long-lived ones cheap. Published: 2026-11-06 Tags: javascript, v8, nodejs, performance, garbage-collection, memory Both runs allocate the same 100 million objects. The second keeps fewer alive, and it spends four times longer in garbage collection: ``` keep 1,000,000 objects alive: 38 ms in GC keep 100,000 objects alive: 155 ms in GC ``` "Hold less memory, pay less GC" sounds obvious. Here it's backwards. --- ## The mental model: movers, not cleaners Think of V8's young-object collector as **movers clearing a room**. They don't throw the trash out one bag at a time. They carry out only what you want to keep, then knock down the whole room. So trash is free. **What costs is everything they have to carry.** > GC charges for survivors, not for garbage. That gives every object one of three fates: 1. **Dies young:** never carried. Almost free. 2. **Lives long:** V8 notices and puts it straight into long-term storage. Cheap. 3. **Lives a while, then dies:** carried out, then thrown away anyway. This is the expensive one. --- ## How it works V8 splits the heap by age, because most objects die young. New objects go into a small **young space**. When it fills, a quick collection called a **scavenge** copies the living objects out and throws away the rest in one go. A dead object is never touched, so it costs nothing. A survivor must be found and copied: anything still reachable from the stack or a global. [How the collector decides that](/p/how-garbage-collection-works). The price of a scavenge depends on how many objects are *alive*, not how many you created. The test uses a ring buffer that keeps the last `keep` objects alive: ```js for (let i = 0; i < 100_000_000; i++) ring[i % keep] = { a: i, b: i }; ``` | Objects kept alive | Time in GC | |---|---| | 1,000 | 20 ms | | 100,000 | 155 ms | | 1,000,000 | 38 ms | *Node 26.13 (V8 14.6), Apple M3 Pro, median of 3 fresh processes, GC time from `perf_hooks`.* - **1,000 kept:** each scavenge carries almost nothing. 100 million objects cost 20 ms. - **100,000 kept:** objects live long enough to be carried, then die. That's fate 3 for nearly everything. - **1,000,000 kept:** V8 notices that objects created on this line keep surviving, so it allocates them directly in old space and stops copying them. This is called **pretenuring**. The proof: turn pretenuring off with `node --no-allocation-site-pretenuring` and the million-object case goes from 38 ms to 1,471 ms. **Honest caveats:** pretenuring is a guess V8 makes while your program runs, not a guarantee. And less total GC time isn't the same as shorter pauses: the biggest kept set also had the longest single pause, 35.9 ms. --- ## In practice Measure before changing anything: ```js import { PerformanceObserver } from "node:perf_hooks"; new PerformanceObserver((list) => { for (const e of list.getEntries()) console.log(e.detail.kind, e.duration.toFixed(1), "ms"); }).observe({ entryTypes: ["gc"] }); ``` If scavenges dominate, you have middle-aged objects. The best fix is to stop creating them: ```js // before: a new object per event, carried once, then dropped ring[i % keep] = { a: i, b: i }; // after: reuse fixed slots const slot = ring[i % keep]; slot.a = i; slot.b = i; ``` At 100,000 kept, GC time fell from 152 ms to 2 ms. The catch: nothing outside the buffer may hold on to a slot, because its data will change. Copy on the way out. A bigger young space (`--max-semi-space-size=64`) also helped, cutting GC to 86 ms without any code change. --- ## Say it in an interview > "V8 uses a generational garbage collector. New objects go into a young space that's cleaned by scavenges, which copy survivors out and drop everything else, so the cost scales with live objects, not with garbage. Short-lived objects are nearly free. The expensive case is objects that survive a scavenge and then die. For objects that keep surviving, V8 can pretenure them, meaning it allocates them directly in old space." --- ## Cheat sheet | Remember | Detail | |---|---| | Young space + scavenge | Copy survivors out, drop the rest | | Cost driver | Number of survivors, not number of allocations | | Cheap | Dies young, or lives long and gets pretenured | | Expensive | Survives a scavenge, then dies | | Fix | Measure with `perf_hooks`, then reuse objects or enlarge the young space | ## TL;DR - A V8 scavenge costs per surviving object, so short-lived garbage is almost free. - Objects that live a while and then die are the worst case: 155 ms of GC here, against 38 ms for keeping ten times more. - Pretenuring is why keeping more was cheaper. Turning it off pushed that case to 1,471 ms. - Measure GC before optimizing, and reuse objects where they die at middle age. --- ## CPU Cache and JavaScript: Why Sorting an Array Can Make Loops 7x Slower URL: https://bitlyst.blog/p/javascript-memory-locality-cpu-cache Summary: How memory locality and CPU cache misses affect JavaScript: why array order changes loop speed for large arrays of objects, and when typed arrays help. Published: 2026-11-06 Tags: javascript, v8, performance, cpu-cache, memory, typed-arrays Same million objects, same loop, same result. The only difference is the order of the items in the array: ``` in creation order: 1.04 ns per element shuffled: 7.51 ns per element ``` ```js for (let i = 0; i < rows.length; i++) total += rows[i].value; ``` From JavaScript's point of view, both runs do exactly the same work. The difference is in where the objects sit in memory. --- ## The mental model: a courier's route Think of the CPU as a **courier** and your objects as houses. An array of objects doesn't hold the houses. It holds a **list of addresses**. When you create objects one after another, V8 builds them side by side on the same street. The courier walks door to door, and every trip to the warehouse brings back the next few houses' packages too. Shuffle or sort the array and you only reorder the address list. The houses don't move. Now every stop is across town. > Sorting an array of objects reorders the addresses, not the objects. --- ## How it works Two hardware tricks make the street walk fast: 1. **Cache lines.** Memory comes into the CPU cache in blocks (128 bytes on this chip). One fetch brings in about three neighboring 40-byte objects for free. 2. **Prefetching.** When the CPU notices you walking steadily forward, it starts fetching ahead of you. Random jumps defeat both. Each read is likely a **cache miss**, so the CPU waits on slower main memory. If that's really the cause, small arrays shouldn't care about order, because they fit in the cache either way. They don't: | Objects | Memory | In order | Shuffled | |---|---|---|---| | 1,000 | 40 KB | 0.77 ns | 0.77 ns | | 100,000 | 4 MB | 0.75 ns | 1.21 ns | | 1,000,000 | 40 MB | 1.04 ns | 7.51 ns | *Node 26.13 (V8 14.6), Apple M3 Pro with a 16 MB L2 cache, median of 5 fresh processes.* 4 MB fits in the 16 MB cache and barely slows down. 40 MB doesn't fit, and takes the big hit. That match is strong evidence, but no hardware counters were read, so it's still an inference. Sorting by an unrelated key gave the same slowdown (7.66 ns). The garbage collector doesn't fix the order for you either. --- ## In practice Make the memory order match the order you read in: ```js // 1. after sorting, copy the objects so they're created in read order rows = rows.map((r) => ({ id: r.id, value: r.value })); // 2. or put the hot number in a typed array: no addresses to follow const values = new Float64Array(rows.length); for (let i = 0; i < rows.length; i++) values[i] = rows[i].value; ``` | Layout | Time per element | |---|---| | Shuffled objects | 7.48 ns | | Shuffled, then copied in read order | 0.91 ns | | `Float64Array` of the field | 0.65 ns | Copying is the small change and brings back almost all the speed. The typed array is fastest because the numbers themselves sit side by side, but you now keep a separate column next to your objects. **Honest stakes:** this is 7.5 ms instead of 1 ms per pass over a million objects. A loop that runs once per request won't care. A loop that constantly crunches big in-memory data will. --- ## Say it in an interview > "A JavaScript array of objects stores references, and the objects live elsewhere on the heap. Objects created in sequence usually sit next to each other, so walking them is cache-friendly: cache lines and prefetching do the work. Sorting or shuffling reorders only the references, so each access jumps around memory and misses the cache. For big data in hot loops, keep objects in traversal order or move hot numbers into a typed array." --- ## Cheat sheet | Remember | Detail | |---|---| | Array of objects | A list of addresses, not the objects themselves | | Fast | Walking memory in order: cache lines + prefetching | | Slow | Random jumps cause cache misses | | Only big data | No effect while the data fits in cache | | Fix | Copy in read order, or use a typed array for hot numbers | ## TL;DR - An array of objects holds addresses, so array order and memory order can differ. - Sorting or shuffling turns a steady walk into random jumps the CPU cache can't help with. - Here a million shuffled objects were 7× slower to sum, while 1,000 objects showed no difference. - Copying after sorting, or using a `Float64Array`, brought the speed back. --- ## Sliced Strings in V8: How a 20-Character ID Keeps 1 MB Alive URL: https://bitlyst.blog/p/v8-sliced-string-memory-retention Summary: Why slice() in V8 can keep a huge parent string alive, how sliced strings cause memory leaks in Node.js, and how to copy a string to release it. Published: 2026-11-06 Tags: javascript, v8, nodejs, performance, memory-leak, strings An array holds 200 short IDs, about 4 KB of text. After a forced garbage collection, the heap is still 200 MB bigger: ``` kept: 200 strings, 3.9 KB of text heap: +200.0 MB ``` Each ID was cut out of a 1 MB JSON string with `slice()`. No closures, no listeners, no globals hold the big strings. --- ## The mental model: a bookmark, not a photocopy When you `slice()` a long string, V8 often doesn't copy the characters. It gives you a **bookmark**: "page 7, 20 characters long, in *that* book." That's fast, and usually fine. But as long as you keep the bookmark, the whole book has to stay on the shelf. > Keep a slice of a big string, and you may be keeping the big string. V8 calls this bookmark a **sliced string**. --- ## How it works Strings in JavaScript can never change, so V8 can safely point into the original instead of copying. The slice is a small object holding a pointer to the parent, an offset and a length: Your code gets no hint at all. `kept[0].length` is 20, and printing or comparing it works normally. There's a cutoff. Very short pieces get copied, because a bookmark wouldn't save any memory: | Kept length | Parent string | |---|---| | 12 characters | freed | | 13 characters | kept alive | *Node 26.13 (V8 14.6), measured with `process.memoryUsage().heapUsed` after two `gc()` calls.* That's why this kind of leak can stay hidden for months, then appear when your IDs switch to UUIDs. `slice` isn't the only way to get a bookmark: | How you got the short string | Keeps the parent alive? | |---|---| | `slice`, `substring` | yes | | `split(...)[i]` | yes | | Regex capture group | yes | | `JSON.parse(big).id` | no, the parser builds new strings | This is V8 behavior, not part of the JavaScript spec. --- ## In practice Copy a piece of a big string before you store it long-term: ```js // before: keeps the 1 MB parent alive cache.set(key, big.slice(7, 27)); // after, in Node cache.set(key, Buffer.from(big.slice(7, 27)).toString()); // after, anywhere cache.set(key, JSON.parse(JSON.stringify(big.slice(7, 27)))); ``` With the `Buffer` copy, heap growth for the 200 IDs went from 200 MB to 0.03 MB. Only do this where the piece outlives the big string: caches, `Map`s, session state, module-level variables. If you slice something and use it right away, the bookmark is the faster choice. To confirm a leak, take a heap snapshot in DevTools, sort by retained size, and look for huge strings held by a `sliced string`. --- ## Say it in an interview > "In V8, `slice`, `substring`, `split` and regex captures can return a sliced string. That's a pointer into the original string, not a copy. If you store that small piece long-term, it keeps the whole original alive and the garbage collector can't free it. The fix is to force a copy, for example with `Buffer.from(s).toString()`, before you put it in a cache." --- ## Cheat sheet | Remember | Detail | |---|---| | Sliced string | A bookmark into the parent string: pointer, offset, length | | Danger | Keeping the slice keeps the whole parent in memory | | Cutoff | 13+ characters become a slice. 12 or fewer are copied | | Safe | `JSON.parse` results are fresh strings | | Fix | Copy before storing long-term: `Buffer.from(s).toString()` | ## TL;DR - V8 can make a slice of a string point into the original instead of copying it. - 200 kept IDs of 20 characters held 200 MB here, because every slice kept its 1 MB parent alive. - Pieces of 12 characters or fewer are copied, so the leak can appear when an ID format gets longer. - Copy before storing long-term, and confirm with a heap snapshot. --- ## Hidden Classes in V8: Why Object Shape Changes Speed URL: https://bitlyst.blog/p/v8-hidden-classes-inline-cache Summary: How V8 hidden classes and inline caches work, why property reads get slower past four object shapes, and how to keep hot code monomorphic. Published: 2026-11-06 Tags: javascript, v8, performance, hidden-classes, inline-cache Same loop, same million objects, same field. The only change is how many *kinds* of object are in the array: ``` 4 shapes: 1.51 ns per read 5 shapes: 3.31 ns per read ``` The loop is a single property read: ```js for (let i = 0; i < items.length; i++) total += items[i].value; ``` Big O is O(n) in both runs. One extra object shape still made each read more than twice as expensive. --- ## The mental model: seating charts Think of every object as having a **seating chart**: a card that says "`title` sits in seat 1, `value` in seat 2." Objects with the same properties, added in the same order, share one chart. V8 calls the chart a **hidden class**. Each line of code that reads `items[i].value` remembers the charts it has seen, so next time it can go straight to the right seat. That memory is the **inline cache**, and it holds up to four charts. > One chart: instant. Up to four: a quick check. Five or more: the line gives up remembering. --- ## How it works Plain JavaScript objects look like dictionaries, but looking up a string on every read would be slow. With a seating chart, V8 only has to check "is this a chart I know?" and then read a fixed seat. You can see the charts yourself with `node --allow-natives-syntax`: ```js const a = { x: 1, y: 2 }, b = { x: 3, y: 4 }, c = { y: 2, x: 1 }; %HaveSameMap(a, b); // true %HaveSameMap(a, c); // false ← same keys, different order ``` A read site moves through three states depending on how many charts it has seen: | Shapes at the read site | Time per read | |---|---| | 1 | 1.04 ns | | 4 | 1.51 ns | | 5 | 3.31 ns | | 64 | 3.39 ns | *Node 26.13 (V8 14.6), Apple M3 Pro, median of 7 fresh processes.* The cost climbs slowly up to four shapes, jumps at exactly five, then stays flat. That jump is the move from "my own short list" to "the shared table." You can get new shapes without meaning to: - **Key order:** `{ x, y }` and `{ y, x }` are different charts. - **Conditional fields:** `if (opt) this.opt = opt` gives one class two shapes. - **`delete`:** removing a property can turn the object into a slower dictionary. --- ## In practice Create objects in one place, with every field set, always in the same order: ```js // before: different shapes depending on the type const book = { title, price, pages }; const song = { title, price, seconds }; // after: one shape, unused fields set to null function makeProduct({ title, price, pages = null, seconds = null }) { return { title, price, pages, seconds }; } ``` Set a field to `null` instead of using `delete`, and assign optional fields every time instead of behind an `if`. **Honest stakes:** going from one shape to five costs about 2 ms per million reads. A click handler will never notice. Parsers, renderers, simulations and serializers can. Change your data model for this only after a profiler points at the loop. --- ## Say it in an interview > "V8 gives objects a hidden class that describes their layout. Objects with the same properties in the same order share one. Each property access caches the hidden classes it has seen. With one it's monomorphic and fast, with up to four it's polymorphic, and with five or more it's megamorphic and falls back to a slower lookup. To keep hot code fast, create objects with the same fields in the same order and avoid `delete`." --- ## Cheat sheet | Remember | Detail | |---|---| | Hidden class | An object's seating chart: which property sits where | | Same chart | Same properties, added in the same order | | Inline cache | Each read site remembers up to 4 charts | | Monomorphic / polymorphic / megamorphic | 1 shape / 2–4 shapes / 5+ shapes | | Shape breakers | Different key order, conditional fields, `delete` | ## TL;DR - Objects with the same properties in the same order share a hidden class. - Each property read caches up to four hidden classes. A fifth makes it fall back to a slower shared lookup. - Here a read cost 1.04 ns with one shape, 1.51 ns with four and 3.31 ns with five. - Only hot loops feel it, so create objects in one place with all fields set, and profile first. --- ## Layout Thrashing: Why Reading offsetWidth in a Loop Freezes the Page URL: https://bitlyst.blog/p/layout-thrashing-forced-reflow Summary: What layout thrashing and forced reflow are, why reading offsetWidth after a style change is slow, and how batching reads and writes fixes it. Published: 2026-11-06 Tags: javascript, browser, performance, layout, dom, rendering This loop updates 1,000 cards once, and it made the browser lay out the page 1,000 times: ```js for (const card of cards) { card.style.height = `${card.offsetWidth / 20}px`; // 123 ms for 1,000 cards } ``` At 60 frames per second you get about 16 ms per frame, so this freezes the page for seven frames. --- ## The mental model: a lazy accountant Think of the browser as a **lazy accountant**. When you change a style, you hand it a receipt, and it puts the receipt on a pile without adding anything up. It does the math once, right before painting the screen. When you read a size like `offsetWidth`, you're asking for the total *right now*. The accountant has to stop and add up the whole pile before answering. > Writes go on the pile. Reads force the math. Ask for the total after every receipt, and the accountant redoes the whole book every time. That's **layout thrashing**. --- ## How it works Setting `card.style.height` only marks the page as "needs layout." That's cheap, so a hundred writes in a row cost almost nothing. Reading `card.offsetWidth` needs a true, current answer. If any change is still pending, the browser pauses your JavaScript and runs layout right away. This is a **forced reflow**. The loop above alternates read, write, read, write, so every read finds a pending write from the card before it: It doesn't matter that the width never actually changes. The browser can't know that without doing the math, so it does the math. `offsetWidth` isn't the only trigger. `offsetHeight`, `clientWidth`, `scrollTop`, `getBoundingClientRect()` and `getComputedStyle()` all force the same thing. Paul Irish keeps a [full list](https://gist.github.com/paulirish/5d52fb081b3570c81e3a). --- ## In practice Read everything first, then write everything: ```js // before: read, write, read, write… for (const card of cards) { card.style.height = `${card.offsetWidth / 20}px`; } // after: all reads, then all writes const widths = cards.map((card) => card.offsetWidth); cards.forEach((card, i) => { card.style.height = `${widths[i] / 20}px`; }); ``` | Cards | Interleaved | Reads, then writes | |---|---|---| | 100 | 2.2 ms | 0.5 ms | | 1,000 | 124.3 ms | 4.8 ms | | 5,000 | 3,029.7 ms | 21.9 ms | *Headless Chrome 156, Apple M3 Pro, median of 7 runs. The interleaved version ran 1 layout per card, the batched version 1 layout in total, counted with the DevTools Protocol's `Performance.getMetrics`.* The cost grows much faster than the card count, because each layout has more cards to place. A list that feels fine with 20 rows in development can freeze the tab with 5,000 rows on a real account. One common fix doesn't help: wrapping the loop in `requestAnimationFrame` measured 120.1 ms against 122.9 ms. It changes *when* the loop starts, not the read-write order inside it. To find thrashing in your own app, record in the DevTools Performance panel and look for layout blocks marked "Forced reflow". They link to the line that caused them. --- ## Say it in an interview > "The browser batches layout. Style changes only mark the page as needing layout, and it runs once before paint. Reading a geometry property like `offsetWidth` while changes are pending forces layout right away. If you alternate reads and writes in a loop, you force one layout per item. That's layout thrashing. The fix is to do all the reads first, then all the writes." --- ## Cheat sheet | Remember | Detail | |---|---| | Writes are cheap | They only mark layout as pending | | Reads can be expensive | `offsetWidth`, `getBoundingClientRect()` and friends force layout if anything is pending | | Thrashing | Read, write, read, write gives one layout per item | | Fix | Batch all reads, then all writes | | Not a fix | `requestAnimationFrame` alone, because the order inside is still wrong | ## TL;DR - The browser waits and runs layout once, right before paint. - Reading a size after a style change forces layout to run immediately. - Alternating reads and writes in a loop forced 1,000 layouts for 1,000 cards here. - Reading everything first and writing after took 1,000 cards from 124 ms to 5 ms. --- ## JavaScript Floating Point: Why 0.1 + 0.2 !== 0.3 URL: https://bitlyst.blog/p/javascript-floating-point-money Summary: Why 0.1 + 0.2 !== 0.3 in JavaScript, how floating-point math drops a cent when converting dollars to cents, and why money should be stored as integers. Published: 2026-11-03 Tags: javascript, numbers, floating-point, money, gotchas Picture a shop where the product page says **$4.35**, the cart says **$4.35**, and the card statement says **$4.34**. Only that one product. A $4.99 item charges $4.99. A $19.99 item charges $19.99. But $4.35 loses a cent every single time. The payment API wants amounts in cents, so somewhere before checkout there's a conversion: ```js const price = 4.35; const amountInCents = Math.floor(price * 100); await charge({ amount: amountInCents }); // amount: 434 ``` `4.35 × 100` is `435`. Primary-school math. Yet `434` is what goes out. --- ## The wrong turn: blaming the rounding `Math.floor` looks like the suspect, so the reflex is to ask whether the payment provider rounds differently, or whether the price in the database was stored as `4.349` by mistake. Neither. Take the database and the provider out completely and run the multiplication alone: ```js 4.35 * 100; // 434.99999999999994 ← there it is ``` `Math.floor` did its job: it rounded `434.999…` down to `434`. The real question is why `4.35 * 100` isn't `435`. --- ## The reveal: computers can't write 4.35 exactly Try writing 1/3 as a decimal. You get `0.3333…` and you have to stop somewhere, so what you write down is a tiny bit smaller than 1/3. Computers have the same problem, but in base 2. JavaScript stores every number as a 64-bit **binary floating-point** value (the IEEE 754 standard). In binary, fractions like 0.1, 0.2 and 0.35 repeat forever, just like 1/3 does in decimal. So the number in memory is the closest value that fits, not the one you typed: ```js (0.1).toPrecision(21); // "0.100000000000000005551" (0.2).toPrecision(21); // "0.200000000000000011102" (4.35).toPrecision(21); // "4.34999999999999964473" ``` `console.log(4.35)` still prints `4.35`, because JavaScript prints the shortest decimal that maps back to the same stored value. The error is real, it's just hidden until arithmetic makes it big enough to show: That's the same reason behind the famous one: ```js 0.1 + 0.2; // 0.30000000000000004 0.1 + 0.2 === 0.3; // false ``` Both inputs are stored slightly too big, the errors add up, and the sum lands on a different binary value than the one `0.3` maps to. This isn't a JavaScript bug. Python, Java, C# and C all give the same answer for `0.1 + 0.2` with their default `double` type. It also explains why only some prices break. `4.35`, `1.15`, `8.20` and `0.07` all land just under the next cent when multiplied by 100. Many other prices happen to land exactly. You can't tell which by looking: ```js 1.15 * 100; // 114.99999999999999 8.2 * 100; // 819.9999999999999 0.07 * 100; // 7.000000000000001 19.99 * 3; // 59.97 (lucky) ``` --- ## The trap inside the fix: toFixed The usual next move is `toFixed(2)`, but it rounds the stored value, not the one you typed: ```js (1.005).toFixed(2); // "1.00" ← expected "1.01" ``` `1.005` is stored as `1.00499999999999989…`, so rounding it to two places correctly gives `1.00`. `toFixed` is fine for display, where it's off by at most a cent on exact halves. It is not a way to make arithmetic correct. --- ## The fix The minimal fix for the conversion is to round to the nearest whole number instead of always down: ```js // before Math.floor(4.35 * 100); // 434 // after Math.round(4.35 * 100); // 435 ``` That works because the error is far smaller than half a cent, so rounding to the nearest integer always snaps back to the right one. The real fix is to stop using fractional dollars at all. Whole numbers are exact in JavaScript up to `Number.MAX_SAFE_INTEGER` (about 9 quadrillion), so if every amount is stored in cents, there's nothing to lose: ```js const prices = [1999, 1999, 1999]; // cents const total = prices.reduce((a, b) => a + b, 0); // 5997, exact // convert only at the edges: for display… new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }) .format(total / 100); // "$59.97" ``` Keep money as integers in the database, in the API, and in your state. Convert to a decimal string only when a human is going to read it. Most payment APIs already work this way, which is the hint. For things that genuinely need decimals, like tax rates, interest or currency conversion, use a decimal library such as `decimal.js` or `big.js`, or do the math on the server in a type built for it, like Postgres `numeric`. --- ## The rule > **Never store money as a fraction. Store whole cents, and turn them into dollars only for display.** --- ## TL;DR - JavaScript numbers are binary floating-point, so decimals like `0.1` and `4.35` are stored as the nearest binary value, not exactly. - That tiny error is why `0.1 + 0.2 === 0.3` is `false` and why `4.35 * 100` is `434.99999999999994`. - `Math.floor` on a converted price can drop a cent; `Math.round` snaps it back to the right integer. - `toFixed(2)` rounds the stored value, so `(1.005).toFixed(2)` is `"1.00"`. Use it for display only. - Store money as integer cents and convert at the edges, or use a decimal library when you need fractional math. --- ## JavaScript Object Key Order: Why Numbers Go First URL: https://bitlyst.blog/p/javascript-object-key-order Summary: Why JavaScript object key order puts integer-like keys first in ascending order, how that silently reorders JSON from your API, and when to use an array or Map. Published: 2026-11-03 Tags: javascript, objects, json, map, gotchas Picture a leaderboard API that does the sorting for you. The highest score comes first, so the frontend only has to render rows in order. You open the network tab and the response looks perfect: ```json { "105": { "name": "player105", "score": 980 }, "42": { "name": "player42", "score": 870 }, "7": { "name": "player7", "score": 640 } } ``` And the page renders this: | Rank | Player | Score | |------|--------|-------| | 1 | player7 | 640 | | 2 | player42 | 870 | | 3 | player105 | 980 | The lowest score is at the top. The leaderboard is exactly upside down, but only by accident: it's actually sorted by user ID. --- ## The wrong turn: blaming the backend The obvious suspect is the server. Maybe the sort runs after serialization, or a cache serves an old response. But the network tab shows the raw body, and it's in the right order. So the order changes somewhere between the response text and the screen. The frontend code is tiny: ```js const data = await res.json(); const rows = Object.values(data); ``` Log each step: ```js const text = await res.text(); console.log(text); // {"105":…,"42":…,"7":…} ✓ sorted by score const data = JSON.parse(text); console.log(Object.keys(data)); // ["7", "42", "105"] ← reordered ``` `JSON.parse` got the keys in one order and gave them back in another. Nothing is shuffling them at random either. They come out in ascending numeric order every time. --- ## The reveal: objects have two kinds of keys Most people learn that object keys "keep insertion order." That's only half true. When JavaScript lists an object's own keys, the spec defines a fixed order with three groups: The reason is arrays. In JavaScript, an array is an object whose keys are `"0"`, `"1"`, `"2"`, and so on. Engines store those index-like keys separately so arrays can be fast, and the spec makes all objects list them first, in numeric order, so arrays always iterate correctly. The catch is how strict "integer-like" is. A key counts only if it's the exact text of a whole number from `0` up to `2³² − 2`: ```js Object.keys({ "10": 1, "2": 2, banana: 3, "1": 4 }); // ["1", "2", "10", "banana"] Object.keys({ "3": 1, "-1": 2, "1.5": 3, "01": 4 }); // ["3", "-1", "1.5", "01"] ← only "3" counts as an index Object.keys({ user_105: 1, user_42: 2 }); // ["user_105", "user_42"] ← plain strings keep insertion order ``` So a leaderboard keyed by `"user_105"` would have worked, and one keyed by `"105"` doesn't. Same data, different key shape. This applies everywhere keys get listed: `Object.keys`, `Object.values`, `Object.entries`, `for...in`, `JSON.stringify`, spreading with `{...obj}`. Since ES2020 the spec pins down `for...in` too, so every modern engine agrees. That's why this bug is so consistent, and why it never shows up while testing with IDs like `"a"` and `"b"`. > **An object is a lookup table, not a list. If order matters, the data has to be a list.** --- ## The fix Send an array. Arrays are the only JSON structure with a guaranteed order, and they carry that order through any parser in any language: ```js // before: order lives in key positions, and gets lost { "105": { "score": 980 }, "42": { "score": 870 } } // after: order lives in the array itself [ { "id": 105, "name": "player105", "score": 980 }, { "id": 42, "name": "player42", "score": 870 } ] ``` If you can't change the API, don't rely on the order you received. Sort on the client using the value that defines the order: ```js const rows = Object.values(data).sort((a, b) => b.score - a.score); ``` And if you need an ordered, keyed collection inside your own code, use a `Map`. A `Map` keeps every key in insertion order, numbers included: ```js const board = new Map([["105", "A"], ["42", "B"], ["7", "C"]]); [...board.keys()]; // ["105", "42", "7"] ✓ ``` `Map` doesn't survive `JSON.stringify` (you get `{}`), so it's for state inside your app, not for the network. --- ## The rule Don't use object key position to carry meaning. Use an array when order matters, and an object or `Map` when you only need to look things up by key. --- ## TL;DR - JavaScript lists object keys in a fixed order: integer-like keys in ascending order, then string keys in insertion order, then symbols. - `JSON.parse` builds a normal object, so a JSON response keyed by numeric IDs comes out sorted by ID, not in the order the server sent. - Only exact whole-number strings like `"7"` count as integer keys; `"01"`, `"-1"`, `"1.5"` and `"user_7"` keep insertion order. - Send ordered data as an array, or sort on the client by the field that defines the order. - Use a `Map` for ordered keyed data inside your app, since it keeps insertion order for every key. --- ## Next.js Link Prefetching: partialPrefetching Explained URL: https://bitlyst.blog/p/nextjs-partial-prefetching-link-list Summary: What a long list of Next.js s really costs in prefetch requests, measured on this blog, and how partialPrefetching shares one App Shell per route instead. Published: 2026-11-03 Tags: nextjs, link, prefetch, performance, app-router The `/blog` page on this site is one long list: 51 posts, 51 ``s. I opened it in a production build, scrolled from top to bottom without clicking anything, and counted the network requests: ``` RSC requests: 83 posts prefetched: 51 of 51 transferred: 576 kB (gzip; 2.7 MB once decoded) ``` Every single post got downloaded in the background because its link scrolled past. Nobody reads 51 posts in a row. That's over half a megabyte spent on pages that, for almost every visitor, will never be opened. --- ## The wrong turn: prefetch={false} everywhere The standard advice, which [an older post on this blog](/p/nextjs-link-prefetch) repeats, is to switch prefetching off for big lists: ```tsx {post.title} ``` That fixes the bandwidth, but it trades it for something worse. Without a prefetch, the router has nothing for that route when you click. Next.js has to fetch it on click before it can show anything, so the instant navigation that made you pick `` in the first place is gone. And it's aimed at the wrong thing. The cost isn't "too many links." It's that each link fetched its own full page. --- ## The reveal: per-link prefetches vs. one shell per route There are two prefetching models in Next.js 16, and the difference is what gets downloaded per link. The old default prefetches each link's page in full. The docs put it plainly: "a page with N links to N routes produced ~N route prefetches." With `partialPrefetching: true`, a link prefetches the route's **App Shell** instead: the parts of the page that don't depend on which post it is, like the layouts and loading states. Every link to `/blog/[...slug]` shares that one shell, fetched when the first of them shows up. The post itself, the part that depends on the URL, loads after you click. It needs Cache Components, which this blog already uses, so turning it on was one line: ```js // next.config.mjs const nextConfig = { cacheComponents: true, partialPrefetching: true, }; ``` --- ## The fix, measured Same page, same scroll, same browser, with the only change being that config value: | Scroll `/blog` top to bottom | Per link (`false`) | Per route (`true`) | |------------------------------|-------------------:|-------------------:| | RSC requests | 83 | **24** | | Post routes prefetched | 51 of 51 | shell + 4 small route-tree requests | | Transferred (gzip) | 576 kB | **90 kB** | | Decoded size | 2.7 MB | 330 kB | That's 84% less data, and the number stops growing with the list. With partial prefetching, the count was 23 requests before scrolling and 24 after. Add another hundred posts and it stays about the same, because they're all the same route. The cost moved to the click, where it belongs. I navigated to the very last post on the list, one that never had its own prefetch. The router made one request for the post itself: 7.7 kB. How I measured, so you can check it: `next build` then `next start` (Next.js 16.4.3), headless Chromium at 1440×900, a fresh browser per run, scrolling 400 px every 250 ms and waiting 3 seconds at the bottom. I counted every resource with `_rsc=` in its URL, using the Resource Timing API's `transferSize`. Three runs per setting gave identical numbers. It ran on localhost, so I'm not quoting request timings. On a real network, the click-time request adds one round trip before the post text appears. > **Long lists of links aren't expensive. Prefetching each link's full page is.** --- ## The rule Before you reach for `prefetch={false}` on a long list, check whether those links share a route. If they do, and you're on Cache Components, turn on `partialPrefetching` and let them share one shell. Save `prefetch={false}` for links that really shouldn't be warmed up at all. --- ## TL;DR - Without partial prefetching, every `` that scrolls into view prefetches its own page, so a list of 51 posts downloaded 576 kB of pages nobody clicked. - `prefetch={false}` saves the bandwidth but makes every click wait for the server. - `partialPrefetching: true` (requires `cacheComponents`) prefetches one App Shell per route, shared by every link to it. - On this blog's index that cut the scroll from 83 requests and 576 kB to 24 requests and 90 kB, and the count no longer grows with the list. - The URL-specific part loads after the click instead; for one post that was a single 7.7 kB request. --- ## Next.js Server Action Runs Twice in Development URL: https://bitlyst.blog/p/nextjs-server-action-runs-twice-dev Summary: Why a Next.js Server Action called from useEffect runs twice in development: React Strict Mode mounts every component twice. What that reveals, and where the call belongs. Published: 2026-11-03 Tags: nextjs, react, server-actions, strict-mode, useeffect Picture a "mark as read" feature. Open a notification, and a Server Action flips it to read in the database and bumps a counter. You add a `console.log` to the action to watch it work, open the page in `next dev`, and the terminal prints: ``` [markAsRead] call #1 [markAsRead] call #2 ``` One page load, two calls. Every time. I rebuilt that exact setup on this blog's codebase (Next.js 16.4, React 19) as a ten-line test page, and got the same thing: two `POST` requests with the same `next-action` id in the network tab, two log lines on the server. --- ## The wrong turn: blaming Next.js Two calls from one load looks like a framework bug. Maybe Next.js retries actions. Maybe the page renders twice on the server and each render fires the action. Maybe HMR left an old copy of the component mounted. None of those hold up. Here's the whole client component: ```tsx "use client"; import { useEffect } from "react"; import { markAsRead } from "./actions"; export function Notification({ id }: { id: string }) { useEffect(() => { markAsRead(id); }, [id]); return

    …

    ; } ``` Server Actions never run during rendering. They run when the browser calls them, and the only thing calling this one is `useEffect`. So the real question is: why does the effect run twice? --- ## The reveal: React mounts everything twice in development Next.js turns on React **Strict Mode** by default in the App Router (the `reactStrictMode` docs say so: it's been `true` by default since Next.js 13.5.1). In development, Strict Mode deliberately stress-tests every component when it first appears: That's why it only happens on localhost. In a production build there's no simulated remount. I checked this on a production build of the blog too: its view counter, which posts from a `useEffect`, sent one `POST` under `next start` and two under `next dev` (the first one cancelled by its cleanup). React does this on purpose. A real user can make a component unmount and mount again: navigate away and back, or a parent that hides and shows it. Strict Mode makes that happen immediately, so you find out now whether your effect survives it. > **Strict Mode isn't calling your action twice. It's showing you that your code would call it twice if the component ever remounted.** --- ## The fix: decide what the call is for There are two kinds of "call an action when this shows up," and they get different fixes. **It's caused by something the user did.** Marking as read, liking, saving, buying. These belong in an event handler or a form, not an effect. The click is the cause, so the click should make the call: ```tsx // before: fires whenever the component mounts useEffect(() => { markAsRead(id); }, [id]); // after: fires once per click // or with a form, which also works before JavaScript loads
    ``` **It's caused by the component being shown.** Page views and analytics are the classic case. Here the effect is the right place, so make the server safe to call twice. This blog's view counter does exactly that: the `POST` handler counts one read per visitor per post per day, so a second request changes nothing. There's also the trick you'll find on Stack Overflow, a ref that remembers it already ran: ```tsx const ran = useRef(false); useEffect(() => { if (ran.current) return; ran.current = true; markAsRead(id); }, [id]); ``` It works: my test page logged one call with it instead of two. But the React docs advise against it, because it silences the warning without fixing the cause. The day the component really remounts, the ref starts over at `false` and you get a second call in production anyway. --- ## The rule If an action changes data because of something the user did, call it from the event that caused it. If it has to run from an effect, make the server handle it arriving twice. --- ## TL;DR - Next.js enables React Strict Mode by default in the App Router, and in development Strict Mode mounts, unmounts and remounts every component. - So a Server Action called from `useEffect` runs twice in `next dev` and once in production. - In a test page on this blog, the action logged two calls in dev; a production build of the view counter sent one request. - Move user-caused mutations (read, like, save) into event handlers or `
    `. - For effects that must call the server, like view tracking, make the endpoint idempotent instead of hiding the second call with a ref. --- ## JavaScript ASI: Why return on Its Own Line Gives undefined URL: https://bitlyst.blog/p/javascript-asi-return-undefined Summary: How automatic semicolon insertion (ASI) turns `return` followed by a newline into `return;`, and the lines where JavaScript refuses to add a semicolon at all. Published: 2026-11-02 Tags: javascript, asi, semicolons, syntax, gotchas Picture a settings panel that crashes the moment it opens: ``` TypeError: Cannot read properties of undefined (reading 'theme') ``` The line that throws is about as boring as code gets: ```js const settings = getDefaultSettings(); applyTheme(settings.theme); // 💥 settings is undefined ``` And `getDefaultSettings` is even more boring. It has no branches, no `await`, no early exit. It builds an object and returns it: ```js function getDefaultSettings() { return { theme: "dark" }; } ``` There's an object right there. The function can't possibly return `undefined`. It does, every time. --- ## The wrong turn: blaming the caller When a value shows up as `undefined`, the natural instinct is to look upstream. Maybe the import is wrong and you're calling a different `getDefaultSettings`. Maybe something mutates the object after it's returned. Maybe the function is async and someone forgot an `await`. Log right at the source: ```js console.log(getDefaultSettings()); // undefined ``` No import, no mutation, no promise. The function itself hands back nothing. The bug is somewhere in five lines, and four of them are braces. --- ## The reveal: JavaScript added a semicolon for you JavaScript lets you leave out most semicolons. To make that work, the parser follows a set of rules called **automatic semicolon insertion**, or ASI. Most of the time ASI is invisible: it adds a semicolon where you clearly meant one. But a few statements are treated as finished the moment a line ends. `return` is one of them. If nothing follows `return` on the same line, the parser doesn't look at the next line to see if the value is there. It ends the statement on the spot. That last step is the cruel part. With one property, the "object" is legal as a block with a label. Add a second property and the parser finally complains: ```js function getDefaultSettings() { return { theme: "dark", fontSize: 14 }; } // SyntaxError: Unexpected token ':' ``` So the bug only stays silent while the object is small, which is exactly when nobody bothers to look at it twice. `return` isn't alone. The spec calls these **restricted productions**: places where a line break is not allowed. The ones you'll actually hit: | You write | JavaScript reads | |-----------|------------------| | `return`⏎`value` | `return; value;` | | `throw`⏎`new Error()` | SyntaxError: a line break isn't allowed after `throw` | | `break`⏎`label` / `continue`⏎`label` | `break; label;` | | `count`⏎`++` | `count; ++…` (the `++` attaches to the next line) | | `(a)`⏎`=> a` | SyntaxError: the arrow must be on the same line as its parameters | --- ## The mirror image: where ASI won't help ASI also fails in the opposite direction. It only inserts a semicolon when the next line can't continue the current one. If the next line starts with `(`, `[` or `` ` ``, it usually can, so no semicolon goes in: ```js const greeting = "hi" [1, 2].forEach((n) => console.log(n)) // TypeError: Cannot read properties of undefined (reading 'forEach') ``` JavaScript reads that as `"hi"[1, 2].forEach(...)`. The comma inside the brackets means "take the last value", so it's `"hi"[2]`, which is `undefined`. Same story with an IIFE: ```js const total = 1 (function () {})() // TypeError: 1 is not a function ``` That's `1(function () {})()`: calling the number `1` like a function. > **ASI adds a semicolon where a line can't continue, never where you meant one.** --- ## The fix Start the value on the same line as `return`. For a multi-line object, open the brace or a parenthesis right after the keyword: ```js // before return { theme: "dark" }; // after return { theme: "dark" }; // also fine, handy for long JSX or expressions return ( someLongCondition && anotherCondition ); ``` And let tools catch the rest: - **Prettier** reformats `return`⏎`{` into `return;` followed by a block, which makes the bug obvious in the diff. - **ESLint**'s `no-unreachable` rule flags the block after the bare `return`. - **TypeScript** marks it as "Unreachable code detected" in the editor. If you write without semicolons, the one habit that matters is the mirror case: put a `;` in front of any line that starts with `(`, `[` or `` ` ``. --- ## The rule Whatever a `return`, `throw`, `break` or `continue` gives back has to start on the same line as the keyword. The parser doesn't look at the next line. --- ## TL;DR - Automatic semicolon insertion ends a `return` statement at the line break, so `return` followed by a value on the next line returns `undefined`. - A one-property object after a bare `return` is still valid code (a labeled block), so nothing errors. Only larger objects throw a SyntaxError. - The same rule applies to `throw`, `break`, `continue`, postfix `++` and arrow functions. - In the other direction, ASI doesn't add a semicolon before lines starting with `(`, `[` or `` ` ``, so those lines merge with the line above. - Keep the returned value on the `return` line, and let Prettier, ESLint's `no-unreachable` or TypeScript flag the rest. --- ## Why map(parseInt) Returns [1, NaN, 3] in JavaScript URL: https://bitlyst.blog/p/javascript-map-parseint Summary: Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3]: map passes the index as parseInt's radix. Plus the Number('') trap hiding in the obvious fix. Published: 2026-11-01 Tags: javascript, arrays, parseint, gotchas, interview Picture a table with a feature users love: select a few rows, refresh the page, and your selection is still there. The selected ids live in the URL: ``` /orders?selected=3,8,12,15,20 ``` You select five orders, hit refresh, and the page comes back with **three** checkboxes ticked: orders **3**, **1** and **8**. Order 1? Nobody touched order 1. And 8 is right, but 12, 15 and 20 are gone. Here's the line that reads the URL back: ```js const selected = params.get("selected").split(",").map(parseInt); // expected: [3, 8, 12, 15, 20] // got: [3, NaN, 1, 1, 8] ``` Five strings in, five numbers out. Just not the five you sent. --- ## The wrong turn: blaming the URL URLs are messy, so that's the natural first suspect. Was the comma encoded as `%2C`? Were there spaces? Is `URLSearchParams` doing something clever? Log the input: ```js params.get("selected"); // "3,8,12,15,20" params.get("selected").split(","); // ["3", "8", "12", "15", "20"] ``` Perfect strings. The URL is innocent. Whatever happened, it happened inside `.map(parseInt)`, a line most of us have written a hundred times without a second thought. --- ## The reveal: map talks more than you think `map` doesn't call your function with one argument. It calls it with **three**: the element, its **index**, and the whole array. ```js ["a", "b"].map((...args) => args.length); // [3, 3] ``` Usually that doesn't matter, because most callbacks ignore the extras. `parseInt` doesn't. Its signature is `parseInt(string, radix)`, where the second parameter is the **number base**. So `.map(parseInt)` quietly turns every index into a base: The classic interview version is the same bug with shorter strings: ```js ["1", "7", "11"].map(parseInt); // parseInt("1", 0) → 1 // parseInt("7", 1) → NaN (no base 1) // parseInt("11", 2) → 3 (binary 11) // result: [1, NaN, 3] ``` Nothing is broken here. `map` passes what it always passes. `parseInt` reads what it always reads. The bug lives in the gap between two functions that were never designed to be plugged into each other. There was a hint, too: `parseInt.length` is `2`. A function that declares two parameters will happily use a second argument if you hand it one. --- ## The fix, and the trap inside the fix The obvious fix is `Number`, which only cares about its first argument: ```js "3,8,12,15,20".split(",").map(Number); // [3, 8, 12, 15, 20] ✓ ``` That works until the URL ends with a stray comma, which is easy to produce, for example when the code that rebuilds the list leaves a trailing separator: ```js "3,8,".split(",").map(Number); // [3, 8, 0] ← order 0? ``` `Number("")` is `0`, not `NaN`. An empty piece of the string silently becomes a real-looking id. `Number` and `parseInt` disagree on more edge cases than you'd expect: | Input | `Number(x)` | `parseInt(x, 10)` | |-------|-------------|-------------------| | `"12"` | `12` | `12` | | `""` | **`0`** | `NaN` | | `" 12 "` | `12` | `12` | | `"12px"` | `NaN` | **`12`** | | `"1e3"` | `1000` | **`1`** | | `"0x1A"` | `26` | **`0`** | Neither is "the safe one." `Number` is strict about junk but turns empty strings into zero. `parseInt` forgives trailing junk, and that can hide bad data. For ids from a URL, you want strict parsing, with empty pieces dropped: ```js const selected = (params.get("selected") ?? "") .split(",") .filter(Boolean) // drop "" from stray commas .map(Number) .filter(Number.isInteger); // drop anything that wasn't a clean number ``` If you do want `parseInt`, give it its own arrow so you choose every argument: ```js .map((s) => parseInt(s, 10)) ``` --- ## The rule > **Don't pass a function you didn't write straight into map, forEach or filter. Wrap it in an arrow that passes exactly what you mean.** `parseInt` is the famous case, but it's not the only one. Any function with optional parameters will grab the index or the array if you let it. `arr.map((x) => fn(x))` costs a few characters and removes the question entirely. --- ## TL;DR - `map` calls its callback with `(element, index, array)`, not just the element. - `parseInt`'s second parameter is the radix, so `.map(parseInt)` parses each string in base 0, 1, 2, 3…, which gives `[1, NaN, 3]` for `['1', '7', '11']`. - `map(Number)` fixes that, but `Number("")` is `0`, so filter out empty strings first. - `Number` and `parseInt` disagree on `""`, `"12px"`, `"1e3"` and `"0x1A"`. Pick the one whose rules match your data. - Wrap library functions in an arrow, `arr.map((s) => parseInt(s, 10))`, so you control every argument. --- ## Next.js cookies() in Root Layout Makes Pages Dynamic URL: https://bitlyst.blog/p/nextjs-cookies-root-layout-dynamic Summary: Reading a cookie with cookies() in the Next.js root layout opts every route out of static rendering. What it cost this blog, measured, and how to fix a theme flash without it. Published: 2026-11-01 Tags: nextjs, app-router, performance, caching, cookies Dark mode on this blog has always had a tiny cheat in it. Before React loads, a little inline script reads your saved theme from `localStorage` and paints the page dark. It works, but it always felt like a hack. The server renders the page without knowing your theme, and a script patches it up in the browser. The "proper" fix seemed obvious. Store the theme in a cookie, read it on the server, render the right class from the start. One line in the root layout: ```tsx // app/layout.tsx import { cookies } from "next/headers"; export default async function RootLayout({ children }) { const theme = (await cookies()).get("theme")?.value; return ( {/* ... */} ); } ``` I tried it on a copy of this blog. Dark mode worked on the very first byte. No script, no patching. Then I ran `next build`. --- ## The build output went all ƒ Before the change, the route table was mostly `○` and `●`: pages rendered once at build time and served as files. ``` ○ / 10m ○ /blog 10m ● /blog/[...slug] (46 posts) 5m ● /tags/[tag] (102 topics) 10m ○ /about 1h ○ /links ``` After the change: ``` ƒ / ƒ /blog ƒ /blog/[...slug] ƒ /tags/[tag] ƒ /about ƒ /links ``` `ƒ` means "server-rendered on demand." I counted the prerendered pages in each build's manifest: | Build | Prerendered HTML pages | |-------|------------------------| | Before | **158** | | After one `cookies()` call | **0** | Every post, every topic page, the home page, even `/links` — a page with no data at all — now renders from scratch on every request. --- ## The wrong turn: "it's just reading a cookie" My mental model was that `cookies()` is a cheap lookup. Read a header, get a string, move on. And it *is* cheap. The expensive part isn't reading the cookie. It's what reading it **means**. A cookie belongs to one visitor. If a page's HTML depends on a cookie, then the HTML can differ for every visitor, so Next.js can't render it once at build time and hand the same file to everyone. The docs call `cookies()`, `headers()` and `searchParams` **Request-time APIs**: use one, and the route has to render at request time. So where you call it decides how much of your app goes dynamic: The root layout wraps every page. One line there is one line in *all* of them. --- ## What it actually cost I served both builds locally with `next start` and measured time to first byte: 30 requests per page after warm-up, median, on an Apple Silicon Mac with Next.js 16.4. | Page | Static build | Cookie build | |------|--------------|--------------| | `/links` (no data) | 1.0 ms | 6.5 ms | | A post page (Redis + Postgres) | 1.4 ms | 13.3 ms | Six to ten times slower, and that's the *best* case: my laptop is the server, so there's no network in between. The bigger difference was in the response headers: ``` # static build Cache-Control: s-maxage=300, stale-while-revalidate=31535700 # cookie build Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate ``` The static page tells a CDN to keep it and serve it from the edge. The cookie page tells every cache in between to **never store it**. In production that means each visitor's request travels to wherever the server runs, waits for a full render, and travels back, instead of being answered by an edge server near them. Every one of those renders also costs compute. All of that for a class name on ``. --- ## The fix: read the cookie in the browser The Next.js docs on [preventing flash before hydration](https://nextjs.org/docs/app/guides/preventing-flash-before-hydration) say it directly: reading the theme cookie in the root layout opts the whole app out of static rendering. Instead, keep the server output generic and read the preference in an inline script that runs **before the first paint**: ```tsx // app/layout.tsx — stays static export default function RootLayout({ children }) { return ( ``` This ensures the correct scheme is applied **before the browser paints anything**. --- ### 3. SSR + hydration safety - The DOM structure (HTML tags and content) is identical on server and client. - Only **CSS variables change**, so React hydration doesn’t complain. - No mismatch, no flicker. --- ### 4. Why Ant Design flashes Ant Design usually toggles a `dark` class **after hydration** using JS: ```js useEffect(() => { document.body.classList.add('dark'); }, []); ``` - Server HTML is always “light”. - First paint = light. - After hydration, `dark` class is applied → second paint. - Visible **flash of light → dark**. --- ## 🧠 Mental Model - **MUI**: Both outfits (light & dark) are in your closet. Before you leave the house, a helper puts the correct one on you. Nobody sees the wrong outfit. - **Ant Design (typical)**: You leave the house in light clothes, then halfway down the street someone swaps you into dark. People see the flicker. --- ## ✅ How to Set Up in Next.js (App Router) ```tsx // app/layout.tsx import { CssVarsProvider, getInitColorSchemeScript } from '@mui/material/styles'; import CssBaseline from '@mui/material/CssBaseline'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {/* Runs before React; sets data-mui-color-scheme to avoid flicker */} {getInitColorSchemeScript()} {children} ); } ``` - `getInitColorSchemeScript()` → ensures correct theme before first paint. - `CssVarsProvider` → enables light/dark CSS variable system. --- ## ✅ Summary - MUI avoids theme flashing by using **CSS variables + an early init script**. - The correct theme is applied **before the first paint**, so users never see the wrong one. - Other UI frameworks often switch after hydration, which causes the flash. ✨ Result: Dark mode feels **native and instant** with MUI. --- ## Deep Copy vs Shallow Copy in JavaScript URL: https://bitlyst.blog/p/deep-vs-shallow-copy Summary: Understand the difference between shallow and deep copies, with examples and pitfalls. Published: 2025-09-26 Tags: javascript, copy, objects, cloning ## 📝 Definitions - **Shallow copy** A new object is created, but its nested objects/arrays are still **referenced** (not copied). - **Deep copy** A new object is created, and all nested objects/arrays are **recursively copied**, so they are fully independent. --- ## 📦 Shallow Copy Examples ```js const obj = { user: "Ali", settings: { theme: "dark" } }; // Shallow copies const copy1 = { ...obj }; const copy2 = Object.assign({}, obj); copy1.user = "Sara"; console.log(obj.user); // "Ali" (independent primitive) copy1.settings.theme = "light"; console.log(obj.settings.theme); // "light" (nested object was shared!) ``` 👉 Only the top-level properties are copied. Nested references still point to the same objects. --- ## 📦 Deep Copy Examples ### Using `structuredClone` (modern JS) ```js const obj = { user: "Ali", settings: { theme: "dark" } }; const deepCopy = structuredClone(obj); deepCopy.settings.theme = "light"; console.log(obj.settings.theme); // "dark" ✅ independent ``` ### Using JSON trick (not recommended for all cases) ```js const deepCopy = JSON.parse(JSON.stringify(obj)); ``` ⚠️ This fails with `Date`, `Map`, `Set`, `undefined`, functions, circular references. ### Using libraries - **Lodash:** `_.cloneDeep(obj)` - **Immer:** handles immutable updates with deep cloning. --- ## 🛑 Pitfalls of Shallow Copy - Mutating nested structures leaks changes: ```js const state = { user: { name: "Ali" } }; const next = { ...state }; next.user.name = "Sara"; console.log(state.user.name); // "Sara" ❌ unexpected mutation ``` - In React/Redux, this can cause **stale renders** because React thinks the state is unchanged (reference is same). --- ## ✅ When to Use - **Shallow copy** is fine when: - Object has only primitives. - You don’t need to mutate nested structures. - Performance is critical and you control object shape. - **Deep copy** is needed when: - You must ensure no shared references. - Working with nested state in frameworks (e.g., Redux). - Serializing complex objects (careful with special types). --- ## 🔍 Performance Considerations - Deep copy is **slower and heavier** because it traverses entire object trees. - Shallow copy is **cheap**, just reassigns top-level references. --- ## ✅ Summary - **Shallow copy**: Copies top-level properties only; nested objects are shared. - **Deep copy**: Recursively copies everything; no shared references. - Use **shallow copy** for flat/simple objects, and **deep copy** when you need complete independence. ✨ Rule of thumb: *If you change a nested value and don’t want it to affect the original → you need a deep copy.* --- ## Why setState Doesn’t Cause Hydration Errors URL: https://bitlyst.blog/p/react-setstate-hydration Summary: Understanding why calling setState after hydration doesn’t produce hydration mismatches in React/Next.js. Published: 2025-09-26 Tags: react, hydration, setState, nextjs ## 🚀 The Core Idea Hydration errors happen **only if the first client render output doesn’t match the server-rendered HTML**. Most `setState` calls you write run **after hydration is finished**, so React treats them as **normal updates**, not as mismatches. --- ## 🕒 Timeline of hydration 1. **Server render** - HTML is generated on the server and sent to the browser. 2. **Client boot** - React runs the **first client render** and **hydrates** the existing DOM. - It compares this client render output with the server HTML. - If they differ, React shows a hydration mismatch warning. 3. **After hydration** - `useEffect` callbacks run. - User events (clicks, inputs) happen. - Calling `setState` here triggers a **normal re-render**; React patches the DOM without comparing to the server again. ✅ So if your **initial client render** matches the server, later `setState` calls will not cause hydration errors. --- ## ❌ When you *do* get hydration errors Hydration warnings occur if the **first client render** differs from the server HTML. Common causes include: - **Non-deterministic values during render** ```js // BAD: server vs client will produce different numbers const id = Math.random(); ``` - **Browser-only values in render** ```js // BAD: only available on client const width = window.innerWidth; ``` - **Different data fetching paths** between server and client. --- ## ✅ Safe Patterns ### 1. Update inside `useEffect` ```tsx "use client"; import { useState, useEffect } from "react"; export default function Example() { const [theme, setTheme] = useState(null); // null matches server useEffect(() => { setTheme(window.localStorage.getItem("theme")); // runs after hydration }, []); return
    Theme: {theme ?? "system"}
    ; } ``` --- ### 2. Mounted flag for client-only UI ```tsx const [mounted, setMounted] = useState(false); useEffect(() => setMounted(true), []); if (!mounted) return null; // matches server's "nothing" return ; ``` --- ### 3. Disable SSR for the component In Next.js, you can skip SSR entirely: ```tsx import dynamic from "next/dynamic"; const ClientComponent = dynamic(() => import("./ClientComponent"), { ssr: false }); ``` --- ### 4. Suppress warnings (last resort) For known benign differences, use: ```tsx {clientOnlyValue} ``` --- ## 🧠 Mental Model - **Hydration compares only once:** server HTML vs first client render. - **`setState` after hydration** = normal re-render, no mismatch. So: make sure your **first render is deterministic**, and you’re safe. --- ## AbortController & AbortSignal URL: https://bitlyst.blog/p/abortcontroller-practical-guide Summary: Everything you need to cancel async work in JS: fetch, streams, custom tasks, React patterns, Node notes, timeouts, races, and common pitfalls. Published: 2025-09-23 Tags: javascript, abortcontroller, abortsignal, fetch, async, react, node `AbortController` is the **standard way** to cancel async work in modern JavaScript. It pairs with **AbortSignal**, which you pass to tasks so they can stop immediately. ![AbortController & AbortSignal](/assets/abortcontroller-practical-diagram.svg) --- ## 1) TL;DR - Create a controller → pass `controller.signal` to your async work. - Call `controller.abort(reason?)` to cancel; consumers see an **`AbortError`** (or `signal.reason`). - Works with **`fetch`**, **streams**, and **your own functions**. ```js const c = new AbortController() const resP = fetch('/api/data', { signal: c.signal }) // later... c.abort('user navigated away') try { await resP } catch (e) { if (e.name === 'AbortError') /* ignore */ } ``` --- ## 2) Core API (with `reason` support) ```js const c = new AbortController() const { signal } = c signal.aborted // boolean signal.reason // any (why it was aborted) c.abort(new DOMException('Timeout', 'AbortError')) // or: c.abort('User left the page') ``` > Tip: If you pass a reason, propagate it in your own tasks. `fetch` will still reject with `AbortError`. --- ## 3) Fetch + Timeouts **A) Easiest: `AbortSignal.timeout(ms)`** ```js // Modern browsers & Node 18+ const res = await fetch('/slow', { signal: AbortSignal.timeout(3000) }) ``` **B) Manual timer** ```js const c = new AbortController() const id = setTimeout(() => c.abort(new DOMException('Timeout', 'AbortError')), 3000) try { const res = await fetch('/slow', { signal: c.signal }) // use res } catch (e) { if (e.name !== 'AbortError') throw e } finally { clearTimeout(id) } ``` **C) Race utilities** ```js // winner-takes-all -> cancel the losers const controllers = [new AbortController(), new AbortController()] const [a, b] = controllers.map(c => fetch('/mirror', { signal: c.signal })) const winner = await Promise.any([a, b]) controllers.forEach(c => c.abort('lost the race')) ``` --- ## 4) Make Your Own Functions Abortable ```js export function wait(ms, signal) { return new Promise((resolve, reject) => { const id = setTimeout(resolve, ms) const onAbort = () => { clearTimeout(id); reject(new DOMException('Aborted', 'AbortError')) } if (signal.aborted) return onAbort() signal.addEventListener('abort', onAbort, { once: true }) }) } ``` **Propagate reason:** ```js const onAbort = () => reject(signal.reason ?? new DOMException('Aborted', 'AbortError')) ``` --- ## 5) Streams & Readers (Browser + Node) ```js const c = new AbortController() const res = await fetch('/stream', { signal: c.signal }) // can be aborted const reader = res.body.getReader({ signal: c.signal }) // abort affects reads too // later c.abort() ``` **Node**: `fetch` in Node 18+ also supports abort; for streams, pipe/reader operations should react to abort and close resources. --- ## 6) React Patterns **A) Cancel on unmount (and on deps change)** ```tsx useEffect(() => { const c = new AbortController() ;(async () => { try { const r = await fetch('/api/search?q=' + q, { signal: c.signal }) setData(await r.json()) } catch (e) { if (e.name !== 'AbortError') console.error(e) } })() return () => c.abort('component unmounted or q changed') }, [q]) ``` **B) Latest-typed value wins (typeahead)** ```tsx const ref = useRef(null) async function onType(v: string) { ref.current?.abort('superseded') const c = new AbortController() ref.current = c try { const r = await fetch('/api?q=' + v, { signal: c.signal }) setOptions(await r.json()) } catch (e) { if (e.name !== 'AbortError') console.error(e) } } ``` --- ## 7) Small Utilities (copy‑paste) ```js // create a controller that auto-aborts after ms export const withTimeout = (ms = 5000) => AbortSignal.timeout(ms) // combine multiple signals -> aborted if ANY aborts export function anySignal(...signals) { const c = new AbortController() const onAbort = (s) => c.abort(s.reason ?? new DOMException('Aborted', 'AbortError')) signals.forEach(s => s.addEventListener('abort', () => onAbort(s), { once: true })) return c.signal } ``` Usage: ```js const c = new AbortController() const s = anySignal(c.signal, AbortSignal.timeout(3000)) fetch('/x', { signal: s }) ``` --- ## 8) Common Pitfalls & Gotchas - **Not wiring the signal** → pass `{ signal }` everywhere the task supports it. - **Forgetting cleanup** → clear timers and remove listeners on abort (use `{ once: true }`). - **Swallowing all errors** → only ignore `AbortError`; surface real failures. - **Global controller reuse** → create fresh controllers per operation to avoid accidental cross‑cancels. - **Overriding reason** → if you care about why, use `abort(reason)` and read `signal.reason` in custom code. --- ## 9) Quick Cheatsheet | Need | Do this | |---|---| | Cancel slow fetch | `fetch(url, { signal: AbortSignal.timeout(ms) })` | | Cancel on unmount | Create `AbortController` in `useEffect`, abort in cleanup | | Cancel prior request (search) | Keep last controller in `ref`, abort before new fetch | | Cancel a batch | Share one controller across requests and call `abort()` | | Keep “why” it was cancelled | `controller.abort('reason'); signal.reason` | --- Happy cancelling ✨ Use AbortController to keep your apps **snappy, correct, and memory‑leak free**. --- ## How useState Works Under the Hood (and Why It Needs use client) URL: https://bitlyst.blog/p/how-usestate-works Summary: Deep dive into React's useState, how it works internally, and why client components are required in Next.js App Router. Published: 2025-09-23 Tags: react, hooks, useState, nextjs, use client ## 1) Where state actually lives - React builds a tree of **Fibers** (one per component instance). - Each function component has a **hook list** stored on its fiber (a tiny linked list/array-like structure). - Every call to `useState(...)` corresponds to one **hook cell** in that list. Order must be stable between renders. --- ## 2) Mount vs. update - **Mount (first render):** - React creates a hook cell with: - `memoizedState`: current value (init arg or result of lazy init function). - `queue`: a queue of pending updates (linked list). - Returns `[state, dispatch]`. - **Update (re-render):** - React **walks the hooks in the same order** and for each `useState`: - Drains the `queue` of updates, applying them in order to produce the new `memoizedState`. - Returns a *stable* `dispatch` function. > Order matters: React identifies each hook by call position in the component. Changing the number/order of hooks between renders breaks this mapping. --- ## 3) What `setState` (dispatch) really does - Calling `setState(payload)` **does NOT mutate immediately**. - It creates an **update object** and pushes it to the hook’s `queue`. - React schedules work on the affected fiber (with an appropriate **priority**). - During the next render, React **reduces** all queued updates to compute the next state. ### Types of payloads - **Value:** `setCount(3)` → replace with `3`. - **Updater function:** `setCount(c => c + 1)` → React calls it with the previous state. - **Lazy init (only on mount):** `useState(() => heavyInit())` runs `heavyInit()` once. --- ## 4) “Async” feel and batching - In React 18+, updates in the same tick are **batched** (browser events, promises, timeouts, etc.). - You might not see new state until the render that **processes** the queue finishes. - `flushSync` can force-sync (use sparingly). --- ## 5) Concurrency & priorities (React 18) - React can **interrupt** a render (e.g., low-priority updates) and resume with fresher data. - `startTransition` marks updates as **transition** (lower priority) so typing stays snappy. - State queues make this possible because React can re-run the reducer pipeline deterministically. --- ## 6) Closures & gotchas - Handlers capture variables from the **render in which they were created**. If you use `setX(x + 1)` inside async code, you may use a stale `x`. Prefer the **functional form**: `setX(prev => prev + 1)`. - Never call hooks in loops/conditions. Keep call order stable. --- # Why `useState` requires `"use client"` in Next.js App Router **Server Components (RSC)** render on the **server**. They: - Must be **serializable output only** (JSX/JSON-like payload). - **Cannot hold runtime client state**, attach event handlers, or access the DOM. - Don’t ship their code to the browser (no client JS). `useState`, `useEffect`, event handlers (`onClick`), etc. require a **client runtime** (browser or React DOM on the client). Therefore: - Any file that uses `useState` must start with: ```tsx "use client"; ``` This marks the file as a **Client Component** so: - It’s bundled for the browser. - It can run hooks, keep state across renders, handle events. - It cannot import **server-only** modules (DB clients, `fs`, server actions directly, etc.). --- ## Mental model - **Server Component** = fetch/compose data, no stateful UI hooks, zero client JS by default. - **Client Component** = interactive UI (state, effects, refs, event handlers). ### Typical pattern (server → client boundary) ```tsx // app/posts/page.tsx (Server Component by default) import PostList from "./PostList"; export default async function Page() { const posts = await fetchPosts(); // server-side data return ; } ``` ```tsx // app/posts/PostList.tsx "use client"; import { useState } from "react"; export default function PostList({ initialPosts }) { const [filter, setFilter] = useState(""); const visible = initialPosts.filter(p => p.title.includes(filter)); return ( <> setFilter(e.target.value)} />
      {visible.map(p =>
    • {p.title}
    • )}
    ); } ``` - The **server** loads data cheaply. - The **client** component handles **state & interactivity**. - Only `PostList` (and its client-only deps) are sent to the browser. --- # Practical tips - Prefer **functional updates** when next state depends on previous: ```ts setCount(c => c + 1); ``` - Use **lazy init** for expensive initial state: ```ts const [value] = useState(() => computeOnce()); ``` - Avoid deriving state you can compute from props during render; compute on the fly or memoize. - If a component only needs state for a tiny part, consider a small **client child** instead of marking a whole page `"use client"`. - Remember: **every `useState` call is per-instance**. Each mounted component instance has its own hook cells & queues. --- ## JavaScript Closures — A Simple Deep Dive URL: https://bitlyst.blog/p/javascript-closures Summary: What closures are, how they work (lexical scope), and how to use them without pitfalls. Published: 2025-09-23 Tags: javascript, closures, scope, lexical environment ## TL;DR A **closure** is when a function **remembers** variables from its **outer scope** even after that outer function has finished running. Think: *“The inner function has a backpack with variables it captured when it was created.”* --- ## The Core Idea (Lexical Scope) - JavaScript uses **lexical (static) scoping**: what you can access is determined by **where** functions are defined in the code (not where they’re called). - When you create a function, JS binds a hidden link to its **Lexical Environment** (scope chain). That link is carried with the function forever → this is the **closure**. ```js function makeCounter() { let count = 0; // captured variable return function () { // inner function forms a closure over `count` count++; return count; }; } const next = makeCounter(); console.log(next()); // 1 console.log(next()); // 2 (still remembers `count`) ``` The `makeCounter` frame is gone, but the inner function keeps `count` alive through its closure. --- ## Why Closures Are Useful 1.**Data privacy / encapsulation** ```js function createBankAccount() { let balance = 0; return { deposit(x) { balance += x; }, withdraw(x) { if (x <= balance) balance -= x; }, getBalance() { return balance; } }; } const acc = createBankAccount(); acc.deposit(100); console.log(acc.getBalance()); // 100 (no direct write access) ``` 2.**Callbacks & async** ```js function greetLater(name) { setTimeout(() => console.log("Hello", name), 500); // `name` is closed over } ``` 3.**Function factories / partial application** ```js const by = key => (a, b) => (a[key] > b[key] ? 1 : -1); users.sort(by("age")); ``` 4.**Memoization** ```js function memoize(fn) { const cache = new Map(); return x => cache.has(x) ? cache.get(x) : (cache.set(x, fn(x)), cache.get(x)); } ``` --- ## Common Gotchas ### 1) Loops with `var` vs `let` ```js for (var i = 1; i <= 3; i++) { setTimeout(() => console.log("var:", i), 0); } // var: 4, var: 4, var: 4 (one shared `i`) for (let j = 1; j <= 3; j++) { setTimeout(() => console.log("let:", j), 0); } // let: 1, let: 2, let: 3 (new binding per iteration) ``` - `var` is function-scoped → the same `i` is captured. - `let`/`const` are block-scoped → each iteration creates a fresh binding. ### 2) Stale closures ```js function makeAdder(n) { return x => x + n; // captures `n` at creation time } const add10 = makeAdder(10); console.log(add10(5)); // 15 // If `n` changes later in outer scope (different ref), this `add10` still uses the captured one. ``` ### 3) Memory considerations - Closures keep referenced variables **alive**. Large objects in closures can extend memory lifetime. - Avoid capturing unnecessary objects; null them out or restructure if needed. --- ## Visualizing the Closure (Mental Model) - When `function () { ... }` is **created**, JS binds a hidden pointer to its **outer environment**. - When the outer function **returns**, that environment may **stay in memory** if any inner function still references it. - Each **call** to the outer function creates a **new environment** (so independent counters, etc.). --- ## Patterns & Recipes ### Module pattern ```js const counterModule = (function () { let value = 0; return { inc() { value++; }, dec() { value--; }, get() { return value; } }; })(); ``` ### Once-only ```js function once(fn) { let called = false, result; return (...args) => { if (!called) { called = true; result = fn(...args); } return result; }; } ``` ### Event handler factories ```js function makeHandler(prefix) { return e => console.log(prefix, e.target.id); } button.addEventListener("click", makeHandler("Clicked:")); ``` --- ## Closures in Frameworks ### React - Every render creates a **new function** with its own closed-over values. - Handlers can capture **stale state**. Prefer functional updates when next state depends on previous: ```js setCount(c => c + 1); ``` - `useRef` holds a stable object and does **not** trigger rerenders; useful to avoid re-creating closures around changing values. ### Node.js - Middleware factories (Express), curried config functions, and async flows rely heavily on closures. --- ## Interview-Style Questions 1.**Define a closure.** A function together with its **lexical environment**, allowing it to remember variables from its defining scope. 2.**Why does `var` + setTimeout in a loop log the same value? How to fix?** Because a single `var` binding is shared. Fix with `let` or an IIFE: ```js for (var i = 1; i <= 3; i++) { (i => setTimeout(() => console.log(i), 0))(i); } ``` 3.**How do closures enable privacy?** By keeping variables in a scope that’s not directly exposed, only through returned functions. 4.**Can closures cause memory leaks?** They can **extend lifetimes**. If you unintentionally retain references (e.g., listeners), memory can grow. Clean up listeners and avoid capturing heavy objects unnecessarily. --- ## Quick Exercises 1.**Create a counter with reset** ```js function counter(start = 0) { let n = start; return { next: () => ++n, reset: () => (n = 0) }; } ``` 2.**Build a simple rate limiter** ```js function rateLimit(fn, ms) { let ready = true; return (...args) => { if (!ready) return; ready = false; fn(...args); setTimeout(() => (ready = true), ms); }; } ``` 3.**Once with error handling** ```js function onceSafe(fn) { let called = false; return (...args) => { if (called) throw new Error("Already called"); called = true; return fn(...args); }; } ``` --- ## Summary - Closure = function **+** its **lexical environment**. - They power privacy, factories, async callbacks, and more. - Watch for loop scoping, stale closures, and unnecessary memory retention. ✨ Master closures, and a lot of JS “magic” becomes predictable. --- ## JavaScript Promises Explained URL: https://bitlyst.blog/p/javascript-promises Summary: A simple but deep dive into how Promises work in JavaScript and why they matter. Published: 2025-09-23 Tags: javascript, async, promise, event loop ## 🚀 What is a Promise? - A **Promise** is a special JavaScript object that represents the result of an asynchronous operation. - It’s like a *placeholder* for a value that will be available **later** (success or failure). Think: *“I promise I’ll give you the result later.”* --- ## 📦 The 3 States of a Promise 1. **Pending** – still waiting for the result. 2. **Fulfilled** – completed successfully, has a value. 3. **Rejected** – failed, has a reason (usually an error). > Once a promise is fulfilled or rejected, it’s **settled** and cannot change again. --- ## 🛠 How to Create a Promise ```js const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve("Done! ✅"); // or reject("Something went wrong ❌"); }, 1000); }); ``` - The function inside `new Promise` runs immediately. - Call `resolve(value)` to fulfill. - Call `reject(error)` to fail. --- ## ⏳ Using a Promise ### With `.then` and `.catch` ```js myPromise .then(result => console.log(result)) // "Done! ✅" .catch(err => console.error(err)); ``` ### With `async/await` (sugar syntax) ```js async function run() { try { const result = await myPromise; console.log(result); // "Done! ✅" } catch (err) { console.error(err); } } ``` --- ## ⚡ Chaining Promises You can chain `.then` calls to transform values step by step: ```js fetch("/data.json") .then(res => res.json()) .then(data => data.items) .then(items => console.log(items)) .catch(err => console.error(err)); ``` Each `.then` returns a **new Promise**, which makes chaining possible. --- ## 🛑 Common Mistakes - **Forgetting to return:** ```js .then(() => { doSomething(); }) // ❌ returns undefined .then(() => doSomething()) // ✅ returns the promise/value ``` - **Mixing callbacks + promises** unnecessarily. - **Not handling errors:** Always end with `.catch` or use `try/catch`. --- ## 🔄 Promise Utilities - `Promise.all([p1, p2])` → waits for all to fulfill, fails fast if one rejects. - `Promise.race([p1, p2])` → returns the first settled (fulfilled or rejected). - `Promise.allSettled([p1, p2])` → waits for all, returns results with status. - `Promise.any([p1, p2])` → first fulfilled, ignores rejections until all reject. --- ## 🔍 How Promises work under the hood - Resolvers (`resolve/reject`) queue their reactions as **microtasks**. - This means `.then`/`catch` callbacks always run **after the current synchronous code**, but **before macrotasks** like `setTimeout`. ```js console.log("Start"); Promise.resolve().then(() => console.log("Microtask")); setTimeout(() => console.log("Macrotask"), 0); console.log("End"); ``` **Output:** ``` Start End Microtask Macrotask ``` --- ## ✅ Summary - A Promise is an object that represents **future values**. - Has 3 states: `pending`, `fulfilled`, `rejected`. - Use `.then/.catch` or `async/await` to consume. - Promises are scheduled as **microtasks** in the event loop, making them powerful for async flow control. --- ✨ Promises are the **foundation** of async/await and modern JavaScript concurrency. --- ## JavaScript is Single-Threaded URL: https://bitlyst.blog/p/js-single-threaded Summary: Understand what it means when people say JS is single-threaded. Published: 2025-09-23 Tags: javascript, event loop, async ## 🚦 What does "single-threaded" mean? - A **thread** is like a worker that can do tasks. - **JavaScript has only one worker** (one thread). - That worker can **do only one thing at a time**. So if JS is running some code, it **cannot** start another piece of code at the same exact time on another thread. --- ## 🛑 Why does this matter? - If one task is **slow** (e.g. a heavy loop or waiting for a file), the single worker gets **stuck**. - This means your whole app (like a webpage) may **freeze** until the task finishes. --- ## 🍕 Analogy Imagine a **pizza chef** in a small restaurant: - There’s only **one chef** (single thread). - If the chef is busy making a pizza, he cannot simultaneously make pasta. - To handle waiting times (like pizza baking in the oven), the chef can **set a timer** and move to the next order. - That timer is like **callbacks, promises, or async/await**. --- ## ⚡ How does JS still feel fast? JavaScript uses the **event loop + asynchronous operations**: - Slow tasks (network calls, timers, etc.) are handed off to the **browser / Node.js background helpers**. - When they’re done, they say “Hey, I’m ready” and the single thread picks it up later. This makes JS *feel* like it’s multitasking, even though only one thing runs at a time. --- ## 💻 Code Example ```js console.log("Start"); setTimeout(() => { console.log("Async task done"); }, 0); console.log("End"); ``` ### Output ``` Start End Async task done ``` 👉 Even though the timeout is `0ms`, the callback is delayed until the main thread finishes current tasks (`Start` and `End`). This proves that **JavaScript has only one main thread**. --- ## ✅ Summary JavaScript is **single-threaded** = one main worker runs tasks one after another. With the **event loop + async**, it can still handle multiple tasks smoothly without blocking. --- ## What is 'use client' in Next.js? URL: https://bitlyst.blog/p/nextjs-use-client Summary: Understand 'use client' in Next.js App Router: what it means, when to use it, and how it works under the hood. Published: 2025-09-23 Tags: nextjs, react, use-client, server-components, frontend Next.js App Router defaults all components to **Server Components**. The `"use client"` directive marks a file as a **Client Component**. ![use client](/assets/nextjs-use-client-diagram.svg) --- ## 1) What does it do? - Placed at the top of a file: `"use client";` - Tells Next.js: render this component **on the client (browser)**. - Without it → the file stays a **Server Component**. ```tsx // Button.tsx "use client"; export default function Button() { return } ``` Without `"use client"`, this would break: event handlers & `useState` only work in the browser. --- ## 2) Why is it needed? - Next.js defaults to **Server Components** for speed & smaller bundles. - `"use client"` is an **escape hatch** when you need client-only features. --- ## 3) When to use it? You need `"use client"` if you use: - React **hooks**: `useState`, `useEffect`, `useRef` - **Event handlers**: `onClick`, `onChange`, … - **Browser APIs**: `localStorage`, `window`, `document` - **Client-only libraries**: Chart.js, React-Quill, etc. --- ## 4) How does it work internally? - Next.js scans for `"use client"` at build time. - That file + its imports → shipped as JS bundle to the browser. - Server Components are stripped to HTML + serialized props. --- ## 5) Mixing Server & Client Components - **Server Components can import Client Components.** - **Client Components cannot import Server Components.** ```tsx // page.tsx (Server Component) import Button from "./Button"; export default function Page() { return (

    Hello

    ); } ``` --- ## 6) Mental Model 🧠 - **Default = Server Component** (fast, no client JS). - Add `"use client"` only where you need **state, events, or browser APIs**. - Sprinkle sparingly → keep most of your tree on the server. --- ⚡ `"use client"` is the switch that brings React interactivity into your Next.js App Router components. --- ## Next.js Page Router vs App Router URL: https://bitlyst.blog/p/page-router-vs-app-router Summary: Understand the key differences between the old Page Router and the new App Router in Next.js. Published: 2025-09-23 Tags: nextjs, react, routing, frontend Next.js gives us **two ways of building apps**: the older **Page Router** (`/pages`) and the newer **App Router** (`/app`). Here’s the difference explained simply: --- ## The Simple Idea - **Page Router (old way):** You put files inside `/pages`. Each file = one route. It’s simple, but limited when your app grows. - **App Router (new way):** You put files inside `/app`. It uses **React Server Components**, layouts, and modern features. It’s more powerful, but needs a bit more learning. --- ## Analogy 🪟 Think of it like building a house: - **Page Router = separate rooms**. Each room (page) has its own door. If you want a shared wall (like a layout), you must rebuild it in every room. - **App Router = house with shared walls**. Rooms (pages) can share layouts, data fetching, and logic without repeating work. --- ## Key Differences 🔑 - **File location:** `/pages` vs `/app` - **Rendering:** Page Router = fully client-side components; App Router = supports **Server Components** - **Layouts:** Page Router = no built-in layouts; App Router = nested layouts by default - **Data fetching:** Page Router = `getServerSideProps` / `getStaticProps`; App Router = async functions inside components (simpler & more flexible) - **Best for:** - Page Router → quick prototypes, small apps - App Router → modern apps, scalable projects, production-ready --- ## Code Example **Page Router** ```tsx // pages/about.tsx export default function About() { return

    About Page

    ; } ``` **App Router** ```tsx // app/about/page.tsx export default function About() { return

    About Page

    ; } ``` --- ## When to Use? - ✅ New project → **App Router** (future of Next.js) - ✅ Old project already using `/pages` → **stay with Page Router** unless you want to migrate - ❌ Don’t mix them in the same route (but you can run both in one project during migration) --- That’s it! 🎉 --- ## JavaScript Event Bus 🚍 (JS + TypeScript) URL: https://bitlyst.blog/p/javascript-event-bus Summary: A polished, practical event bus pattern with minimal JS, a strongly-typed TS version, wildcards, once-handlers, and React usage tips. Published: 2025-09-21 Tags: javascript, event-bus, pubsub, architecture, typescript, react **Event Bus** = simple **publish/subscribe** hub so modules can talk **without direct references**. ![JavaScript Event Bus](/assets/event-bus-diagram.svg) --- ## 1) Why use an Event Bus? - **Decoupling**: publishers don't import subscribers. - **Reusable communication**: one signal → many independent reactions. - **Great for**: auth signals, toasts, analytics, cross-feature coordination. > Use a bus **sparingly**. For large apps, prefer a structured state manager (Redux, Zustand, Vuex) for core state. --- ## 2) Minimal, Fast JavaScript Implementation ```js // eventBus.js export class EventBus { constructor() { this.map = Object.create(null) } on(event, cb) { (this.map[event] ||= new Set()).add(cb) return () => this.off(event, cb) // unsubscribe helper } once(event, cb) { const off = this.on(event, (p) => { off(); cb(p) }) return off } off(event, cb) { const set = this.map[event]; if (!set) return set.delete(cb); if (set.size === 0) delete this.map[event] } emit(event, payload) { const call = (set) => set && set.forEach(fn => fn(payload)) // direct call(this.map[event]) // simple wildcard: "user:*" matches "user:login" const star = event.split(':')[0] + ':*' call(this.map[star]) } } // Usage export const bus = new EventBus() const off = bus.on('user:login', (u) => console.log('hello', u.name)) bus.once('user:login', () => console.log('toast shown once')) bus.emit('user:login', { name: 'Alice' }) // later off() ``` **Why this version?** - `Set` avoids duplicates, `once` auto-cleans, wildcard channel `"domain:*"` is lightweight. --- ## 3) Strongly-Typed TypeScript Bus (safe contracts) ```ts // typedBus.ts type Events = { 'user:login': { name: string } 'user:logout': void 'chat:message': { text: string; from: string } 'user:*': unknown // wildcard channel (optional) } export class TypedBus> { private map: { [K in keyof E]?: Set<(p: E[K]) => void> } = {}; on(event: K, cb: (payload: E[K]) => void) { (this.map[event] ||= new Set()).add(cb) return () => this.off(event, cb) } once(event: K, cb: (payload: E[K]) => void) { const off = this.on(event, (p) => { off(); cb(p) }) return off } off(event: K, cb: (payload: E[K]) => void) { const set = this.map[event]; if (!set) return set.delete(cb); if (set.size === 0) delete this.map[event] } emit(event: K, payload: E[K]) { const call = (set?: Set<(p: any) => void>) => set?.forEach(fn => fn(payload)) call(this.map[event]) // naive wildcard match: prefix + ':*' const star = (String(event).split(':')[0] + ':*') as keyof E call(this.map[star]) } } export const bus = new TypedBus() ``` **Contract benefits**: Autocomplete for event names & payload shapes; compile-time safety. --- ## 4) React Usage Patterns **A. Global bus instance** (simple apps) ```tsx // bus.ts export const bus = new EventBus() // Navbar.tsx useEffect(() => bus.on('user:login', () => setOpen(true)), []) // LoginForm.tsx const submit = () => bus.emit('user:login', { name: 'Alice' }) ``` **B. Context + scoped bus** (feature isolation / testability) ```tsx const BusContext = createContext<{ bus: EventBus } | null>(null) export function BusProvider({ children }) { const [bus] = useState(() => new EventBus()) return {children} } export function useBus() { const ctx = useContext(BusContext); if (!ctx) throw new Error('No BusProvider') return ctx.bus } ``` **C. Clean up subscriptions** ```tsx useEffect(() => { const off = bus.on('toast:show', setToast) return off // auto-unsubscribe on unmount }, []) ``` --- ## 5) Node.js: you already have one ```js import { EventEmitter } from 'node:events' const bus = new EventEmitter() bus.on('ping', () => console.log('pong')) bus.emit('ping') ``` Use Node's `EventEmitter` for server code; for browsers and shared libs, a tiny custom bus is fine. --- ## 6) Tips & Pitfalls - **Name events with namespaces**: `user:login`, `cart:itemAdded`. - Provide a **registry doc** (events & payloads) to avoid mismatches. - **Avoid global everything**: consider **scoped buses** per feature. - **Memory leaks**: always unsubscribe on unmount; `once` helps. - Prefer **state managers** for shared state; use the bus for **signals**. --- ## 7) Quick Cheatsheet | Need | Suggestion | |---|---| | One-off global signal (toast/auth) | Event bus | | Complex shared state | Redux/Zustand/Context | | Typed payloads & autocomplete | TypeScript `TypedBus` | | Only one reaction allowed | `once` | | Fan-out to many listeners | plain `emit` or wildcard | --- ## React Higher-Order Components (HOC) URL: https://bitlyst.blog/p/react-hoc-guide Summary: Understand Higher-Order Components (HOCs) in React with examples, use cases, downsides, and a comparison to hooks. Published: 2025-09-21 Tags: react, hoc, patterns, frontend A **Higher-Order Component (HOC)** is a **function that takes a component and returns a new component** with extra features. --- ## 1. Analogy ☕ Think of a coffee cup (your component). A HOC is like a **sleeve** you put around the cup: it doesn’t change the coffee, but it adds insulation (extra functionality). --- ## 2. Why Use HOCs? - **Reusability** → extract and share common logic. - **Separation of concerns** → UI components stay simple, HOCs handle cross-cutting logic. - **Composition** → wrap components with multiple behaviors. --- ## 3. Example ```tsx // HOC that adds a loading spinner function withLoading

    (Component: React.ComponentType

    ) { return function WrappedComponent(props: P & { loading: boolean }) { if (props.loading) { return

    Loading...
    } return } } // Usage function UserProfile({ name }: { name: string }) { return

    {name}

    } const UserProfileWithLoading = withLoading(UserProfile) // Render ``` 👉 If `loading` is true → show spinner. Otherwise, show `UserProfile`. --- ## 4. Common Use Cases - **Auth wrapper** → redirect if not logged in. - **Analytics wrapper** → log component views. - **Data fetching** → provide fetched data as props. - **UI wrappers** → error boundaries, animations, styles. --- ## 5. Downsides - Can cause **wrapper hell** (too many nested HOCs). - Makes React DevTools component tree messy. - Harder to type with **TypeScript**. - Modern React often prefers **Hooks** instead. --- ## 6. HOCs vs Hooks | Feature | HOCs ✅ | Hooks ✅ | |----------------------------|---------|----------| | Share logic across comps | ✔️ Yes | ✔️ Yes | | Simple composition | ❌ Can get messy | ✔️ Very clean | | Works in class components | ✔️ Yes | ❌ No (hooks = function comps only) | | DevTools readability | ❌ No | ✔️ Clear | | Modern React preference | ⚠️ Legacy pattern | ✔️ Recommended | --- ## 7. Quick Mental Model 🧠 - **HOC = function wrapper → adds behavior → returns new component.** - Use it for **auth, logging, theming, analytics wrappers**. - Prefer **hooks** for most new code. --- ⚡ That’s it! HOCs are still useful in some cases, but hooks are the modern go-to for sharing React logic. --- ## JavaScript's Event Loop — Simple Guide (with SVG Timeline) URL: https://bitlyst.blog/p/javascript-event-loop Summary: Event loop explained with a clean SVG timeline showing the actual execution order: Start → End → Promise → Timeout. Published: 2025-09-20 Tags: javascript, event-loop, async, promises, frontend, diagram The **event loop** lets JavaScript handle async tasks on a single thread. ## Example Code ```js console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); ``` **Output:** `Start → End → Promise → Timeout` --- ## Visual Timeline (SVG) ![Event Loop SVG](/assets/event-loop-timeline.svg) --- ## Why this order? - `Start` and `End` are synchronous → run immediately on the **call stack**. - `Promise.then` is a **microtask** → runs **before** macrotasks. - `setTimeout` callback is a **macrotask** → runs after microtasks drain. --- ## Microtask vs Macrotask in JavaScript — With Node.js vs Browser Notes URL: https://bitlyst.blog/p/javascript-microtask-macrotask-node-vs-browser Summary: Understand microtasks and macrotasks across browsers and Node.js, including process.nextTick, setImmediate, and event loop phases. Published: 2025-09-20 Tags: javascript, event-loop, microtask, macrotask, nodejs, browser ## Recap (Browser) - **Microtasks**: `Promise.then/catch/finally`, `queueMicrotask`, `MutationObserver` - **Macrotasks**: `setTimeout`, `setInterval`, `requestAnimationFrame`, DOM events - **Order per tick**: run script → **drain all microtasks** → possibly render → then the next **macrotask**. --- ## Node.js Event Loop Differences Node.js has **phases** in its event loop (simplified): 1) **Timers** → `setTimeout` / `setInterval` callbacks 2) **Pending Callbacks** 3) **Poll** → I/O callbacks; may block waiting for I/O 4) **Check** → `setImmediate` callbacks 5) **Close Callbacks** After each phase, Node runs microtask queues in this order: - **`process.nextTick`** queue (✅ runs *before* promise microtasks) - **Promise microtasks** (jobs scheduled by `Promise.then` / `queueMicrotask`) ### Key takeaways - `process.nextTick` **always runs before** other microtasks and **before** moving to the next phase. Overuse can **starve** the loop. - `setImmediate` runs in the **Check** phase. - `setTimeout(..., 0)` runs in the **Timers** phase of a **later** tick. - Order of `setTimeout(…,0)` vs `setImmediate` can vary: - After I/O, **`setImmediate` tends to run first** (since the loop is already at the Check phase). - Without I/O, **timers may run first** (implementation- and timing-dependent). --- ## Example: Node.js ordering ```js // node-order.js setTimeout(() => console.log('timeout'), 0); setImmediate(() => console.log('immediate')); Promise.resolve().then(() => console.log('promise microtask')); process.nextTick(() => console.log('nextTick microtask')); ``` **Typical Node output:** ``` nextTick microtask promise microtask [ either 'immediate' or 'timeout' first, scenario-dependent ] ``` Why: - `process.nextTick` runs **before** other microtasks. - Promise microtasks run next. - Then the loop continues to a phase where either `setImmediate` or `setTimeout` fires first. > Tip: If you place the scheduling **inside an I/O callback** (e.g., `fs.readFile`), `setImmediate` is more likely to run before `setTimeout`. --- ## Example: Browser ordering ```html ``` **Browser output:** ``` promise microtask timeout ``` --- ## Quick Matrix | API / Concept | Browser Microtask | Browser Macrotask | Node Microtask | Node Macrotask | |-------------------------|-------------------|-------------------|----------------|----------------| | `Promise.then` | ✔️ | ❌ | ✔️ | ❌ | | `queueMicrotask` | ✔️ | ❌ | ✔️ | ❌ | | `MutationObserver` | ✔️ | ❌ | ❌ (browser only) | ❌ | | `setTimeout / setInterval` | ❌ | ✔️ | ❌ | ✔️ (Timers) | | `requestAnimationFrame` | ❌ | ✔️ (render step) | ❌ | ❌ | | `setImmediate` | ❌ | ❌ | ❌ | ✔️ (Check) | | `process.nextTick` | ❌ | ❌ | ✔️ (before other microtasks) | ❌ | --- ## Mental Model 🧠 - **Browser**: script → **microtasks** (Promises) → **macrotask** (timeout) → render. - **Node**: phase → **nextTick** → **Promise microtasks** → next phase; `setImmediate` in **Check**, timers in **Timers**. Use `process.nextTick` sparingly (it’s *too* eager), and prefer Promise microtasks for normal “run right after” semantics. --- # Microtask vs Macrotask — Visual Diagram This diagram shows how a **microtask** (Promise) runs **before** a **macrotask** (`setTimeout`) after the script finishes. ![Microtask vs Macrotask — Visual Diagram](/assets/microtask-macrotask-diagram.svg) --- That’s it — now you can reason about microtasks/macrotasks across both environments with confidence. --- ## Next.js App Router Caching — Cheat Sheet URL: https://bitlyst.blog/p/nextjs-caching-cheatsheet Summary: A compressed reference of Next.js caching layers and controls (App Router). Published: 2025-09-20 Tags: nextjs, caching, app-router, performance Next.js caches at **multiple layers**. This guide compresses the [official caching docs](https://nextjs.org/docs/app/guides/caching) into a quick reference. --- ## 1. The Cache Layers - **React Request Memoization** - Deduplicates repeated `fetch` calls during a single render. - Cleared after render; not persistent across requests. - **Data Cache (server, persistent)** - Stores `fetch` results across requests. - Controlled by `cache` and `next.revalidate`. - `force-cache` → uses it. - `no-store` → skips it. - `next.revalidate` → ISR-style time-based revalidation. - Can also revalidate **on-demand** (`revalidateTag`, `revalidatePath`). - **Full Route Cache (server)** - Stores rendered RSC/HTML for static routes. - Invalidated when data revalidates or on redeploy. - Dynamic routes skip this. - **Router Cache (client)** - Stores prefetched RSC payloads for `` navigations. - Cleared by `router.refresh()` (client-only). --- ## 2. Controlling Caching ### `fetch` options ```ts // Always cache (default for static) await fetch(url, { cache: 'force-cache' }) // Never cache (dynamic) await fetch(url, { cache: 'no-store' }) // ISR (revalidate every 60s) await fetch(url, { next: { revalidate: 60 } }) ``` ### On-demand revalidation ```ts import { revalidateTag, revalidatePath } from 'next/cache' // Inside server action or API route await revalidateTag('products') await revalidatePath('/dashboard') ``` 👉 In a **Server Action**, this also clears the **client Router cache** instantly. ### Route-level config ```ts // Opt out of Full Route Cache (force dynamic render) export const dynamic = 'force-dynamic' // Skip all caches export const revalidate = 0 // Default all fetches to no-store export const fetchCache = 'default-no-store' ``` Also: using `cookies()` or `headers()` in a route marks it dynamic. --- ## 3. What Invalidates What? - **Data revalidation** (time-based or on-demand) → updates Data Cache + invalidates Full Route Cache. - **Redeploy** → clears Full Route Cache (not Data Cache). - **`router.refresh()`** → clears only the **client Router Cache**. --- ## 4. Browser vs Server `fetch` - In **browser** → `cache` controls the HTTP cache. - In **Next.js server** → `cache` controls the **Data Cache** behavior. --- ## 5. Defaults - **Static rendering**: Data Cache + Full Route Cache enabled. - **Dynamic rendering**: `fetch` runs every request. - `` populates Router Cache automatically. --- ## 6. Quick Decision Table | Situation | What to do | |----------------------------------------|------------| | Always serve fresh (auth dashboards) | `fetch(..., { cache: 'no-store' })` or `export const revalidate = 0` | | ISR (update every N seconds) | `fetch(..., { next: { revalidate: N } })` | | On-demand revalidation (CMS updates) | Use `revalidateTag` / `revalidatePath` | | Force full dynamic rendering | `export const dynamic = 'force-dynamic'` | | Skip client cache after action | Call `router.refresh()` | --- ⚡ Use `no-store` for truly dynamic, `revalidate` for ISR, and `revalidateTag/Path` for precise invalidation. Combine with route config to balance **freshness vs performance**. --- ## React useRef vs useState — When to Use Which URL: https://bitlyst.blog/p/react-useref-vs-usestate Summary: A simple guide to understanding when to use useRef and useState in React, with examples, mental models, and a quick cheatsheet. Published: 2025-09-17 Tags: react, hooks, useRef, useState, frontend React gives us `useState` and `useRef` to store values across renders. But they behave differently. --- ## 1. useState - Stores **data that affects rendering**. - When state changes → component **re-renders**. - Best for values you want to **show in the UI**. ```tsx function Counter() { const [count, setCount] = useState(0) // 🔄 triggers re-render return ( ) } ``` Every click updates `count` → React re-renders → UI shows new value. --- ## 2. useRef - Stores a **mutable value** that survives re-renders. - Updating `.current` **does NOT trigger re-render**. - Best for storing **DOM nodes** or values that don’t affect UI. ```tsx function Timer() { const intervalRef = useRef(null) // 🗃️ stable across renders function start() { intervalRef.current = window.setInterval(() => { console.log("tick") }, 1000) } function stop() { if (intervalRef.current) clearInterval(intervalRef.current) } return ( <> ) } ``` Here, `intervalRef` keeps the timer ID but doesn’t cause re-renders. --- ## 3. When to Use Which? ✅ **Use `useState` when…** - The value **affects rendering**. - UI should update when value changes. - Examples: counters, form fields, theme toggles, fetched data. ✅ **Use `useRef` when…** - The value should **persist across renders** but doesn’t affect UI. - You want to avoid unnecessary re-renders. - Examples: - Accessing DOM elements (`ref={myRef}`) - Storing timer IDs, WebSocket connections - Holding previous values for comparison --- ## 4. Example: Using Both Together ```tsx function InputFocus() { const [text, setText] = useState("") // shows in UI const inputRef = useRef(null) // reference to DOM return ( <> setText(e.target.value)} /> ) } ``` - `useState` stores the text (triggers render). - `useRef` stores a DOM reference (no render needed). --- ## 5. Quick Mental Model 🧠 - **useState = for UI** → change → re-render. - **useRef = for storage** → change → no re-render. --- ## 6. Cheatsheet Table | Feature | `useState` ✅ | `useRef` ✅ | |---------------------|---------------|-------------| | **Triggers re-render on change** | ✔️ Yes | ❌ No | | **Best for** | UI values (text, count, toggles) | DOM refs, timers, storage | | **Persists across renders** | ✔️ Yes | ✔️ Yes | | **Mutable without causing render** | ❌ No | ✔️ Yes | | **Common uses** | Form inputs, counters, fetched data | Focus input, store IDs, previous values, WebSocket refs | --- ⚡ That’s it! Now you know when to reach for `useState` and when to grab `useRef` — and have a cheatsheet for quick reference. --- ## When Should You Use Dynamic Import in React/Next.js? (With Performance Comparison) URL: https://bitlyst.blog/p/when-to-use-dynamic-import-with-performance Summary: A practical guide to dynamic imports with real-world examples and a before/after bundle-size comparison using next-bundle-analyzer. Published: 2025-09-17 Tags: react, nextjs, dynamic-import, performance, bundle-size Dynamic import lets you **lazy load components** so they’re only loaded when needed, instead of bundling everything up front. --- ## 1) What is Dynamic Import? ```tsx // Static import (always in initial bundle) import BigChart from "./BigChart" // Dynamic import (code-split, loaded on demand) import dynamic from "next/dynamic" const BigChart = dynamic(() => import("./BigChart")) ``` --- ## 2) Why Use It? ✅ **Faster initial load** (smaller JS) ✅ **Conditional loading** (only when needed) ✅ **Avoid SSR issues** for client-only libs (`{ ssr: false }`) --- ## 3) Good Use Cases - Heavy, optional widgets: **charts**, **maps**, **rich editors**, **modals** - Client-only libs that access `window` - Feature flags / A/B tests - Dashboards with many expandable panels --- ## 4) Real-World Examples ### a) Rich text editor (`react-quill`) ```tsx import dynamic from "next/dynamic" const RichTextEditor = dynamic(() => import("react-quill"), { ssr: false }) export default function Page() { return (

    Create Post

    ) } ``` ### b) Charts (`react-chartjs-2`) ```tsx import dynamic from "next/dynamic" const Chart = dynamic(() => import("react-chartjs-2"), { ssr: false }) export default function Dashboard() { return (

    Analytics

    ) } ``` --- ## 5) Performance Comparison (Before vs After) Below is a **sample** comparison showing how dynamic import can change bundle breakdown. Use the **measurement steps** in the next section to produce your **actual numbers**. | Chunk/Metric | Before (static import) | After (dynamic import) | |-----------------------------------|-------------------------|------------------------| | Initial JS (first load) | 420 KB | 240 KB | | `react-quill` in initial bundle | 170 KB | 0 KB (lazy) | | `react-chartjs-2` in initial | 95 KB | 0 KB (lazy) | | Route JS (dashboard page) | 210 KB | 80 KB | | Number of JS chunks | 9 | 13 | | Largest Contentful Paint (LCP)* | 2.4s | 1.8s | \* LCP depends on network/device; treat this as illustrative. Your actual metrics may vary. --- ## 6) How to Measure It in Your App ### Option A — `@next/bundle-analyzer` 1. **Install** ```bash npm i -D @next/bundle-analyzer ``` 2. **Configure** `next.config.js` ```js // next.config.js const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true', }) module.exports = withBundleAnalyzer({ // your Next.js config }) ``` 3. **Build & Analyze** ```bash ANALYZE=true next build # Then open the generated treemaps (usually in .next/analyze) to inspect chunks. ``` ### Option B — Inspect build output ```bash next build # Check "First Load JS shared by all" and per-route sizes in terminal output. ``` ### Option C — Web Vitals in production - Track **LCP/TTFB/CLS** before vs after with your analytics (e.g., Vercel Web Analytics, Sentry, or custom). --- ## 7) When NOT to Use It - Small, shared UI primitives (buttons, inputs) - Components present on **every** route (header, footer) - Over-splitting into too many tiny chunks (extra requests/latency) --- ## 8) Cheatsheet (TL;DR) | Situation | Use Dynamic Import? | |-------------------------------------------|----------------------| | Heavy/optional components | ✔️ Yes | | Client-only libraries (need `window`) | ✔️ Yes | | Feature flags / A/B features | ✔️ Yes | | Always-used layout (navbar/footer) | ❌ No | | Small common components | ❌ No | --- **Pro tip:** Pair dynamic imports with **skeletons** or **loading placeholders** so the UI feels responsive while chunks load. --- ## Git Rebase vs Git Merge — Simple Guide URL: https://bitlyst.blog/p/git-rebase-vs-merge-with-diagrams Summary: Understand the difference between git rebase and git merge with analogies, ASCII diagrams, and visual commit history diagrams. Published: 2025-09-16 Tags: git, version-control, rebase, merge, basics When working with branches, you often need to **bring changes from `main` into your feature branch**. There are two main ways to do this: **merge** and **rebase**. --- ## 1. Git Merge **What it does**: Combines histories by creating a **new merge commit**. **History**: Keeps both timelines intact (branching visible). **Analogy**: Two rivers join into one bigger river. ```bash git checkout feature/login git merge main ``` Result (ASCII): ``` A---B---C main \ D---E---M feature/login ``` Visual diagram: ![Git Merge Diagram](https://wac-cdn.atlassian.com/dam/jcr:4639eeb8-e417-434a-a3f8-a972277fc66a/02%20Merging%20main%20into%20the%20feature%20branh.svg?cdnVersion=2969) --- ## 2. Git Rebase **What it does**: Moves your branch to start **on top of main**, rewriting commits. **History**: Linear, no merge commit. **Analogy**: Pretend you started work after main’s latest changes. ```bash git checkout feature/login git rebase main ``` Result (ASCII): ``` A---B---C---D'---E' feature/login ``` Visual diagram: ![Git Rebase Diagram](https://wac-cdn.atlassian.com/dam/jcr:3bafddf5-fd55-4320-9310-3d28f4fca3af/03%20Rebasing%20the%20feature%20branch%20into%20main.svg?cdnVersion=2969) --- ## 3. When to Use - **Merge** ✅ - Shared branches. - Preserves history exactly. - Default in big teams. - **Rebase** ✅ - Personal feature branches (before PR/MR). - Clean, linear history. - Avoid on public/shared branches (rewrites history). --- ## 4. Quick Mental Model 🧠 - **Merge** = "Add a commit that says: we combined work." - **Rebase** = "Replay my work as if I started from your latest state." --- ## 5. Interview Answer *"Merge preserves history with a merge commit, while rebase rewrites commits on top of the target branch for a linear history. Use merge for shared branches, and rebase to clean up local branches before merging."* --- ⚡ That’s it! Now you know when to use `merge` vs `rebase`. Check out the [Git Rebase vs Git Merge](https://www.atlassian.com/git/tutorials/merging-vs-rebasing) page for more information. --- ## Frontend Design Patterns — A Practical Guide URL: https://bitlyst.blog/p/frontend-design-patterns Summary: A concise, example‑driven overview of the most useful frontend patterns for modern React/Next.js apps. Published: 2025-09-15 Tags: frontend, design-patterns, react, architecture This guide focuses on **practical patterns** you can apply today in React/Next.js (but most concepts are framework‑agnostic). --- ## Core Principles - **Composition over inheritance**: build small parts and combine them. - **Single responsibility**: each component does one thing well. - **Lift state up** only when multiple children need it. - Prefer **pure/controlled** components for predictability. - Co-locate logic, styles, tests **near the component**. --- ## Component Patterns ### 1) Presentational vs Container (Smart/Dumb) - **Presentational**: UI only, gets data via props. - **Container**: handles data fetching/state, passes props down. ```jsx // Container function UserCardContainer() { const { data } = useQuery({ queryKey: ['user'], queryFn: fetchUser }) return } // Presentational function UserCard({ user }) { return
    Hello, {user.name}
    } ``` ### 2) Controlled vs Uncontrolled - **Controlled**: value lives in React state. - **Uncontrolled**: DOM keeps the value; you read refs when needed. ```jsx // Controlled function NameInputControlled() { const [name, setName] = useState('') return setName(e.target.value)} /> } // Uncontrolled function NameInputUncontrolled() { const ref = useRef(null) const submit = () => console.log(ref.current?.value) return <> } ``` ### 3) Compound Components Let parent own state; children communicate via context. ```jsx const TabsContext = createContext(null) export function Tabs({ children }) { const [active, setActive] = useState(0) return {children} } Tabs.List = function List({ children }) { return
    {children}
    } Tabs.Tab = function Tab({ index, children }) { const ctx = useContext(TabsContext) return } Tabs.Panel = function Panel({ index, children }) { const ctx = useContext(TabsContext) return ctx.active===index ?
    {children}
    : null } ``` ### 4) Render Props / HOCs / Custom Hooks - Prefer **custom hooks** in modern React for logic reuse. ```jsx // Custom hook (logic) function useCountdown(ms: number) { const [left, setLeft] = useState(ms) useEffect(() => { const id = setInterval(() => setLeft(v => Math.max(0, v-1000)), 1000); return () => clearInterval(id) }, []) return left } // Usage function OfferTimer() { const left = useCountdown(10_000) return

    Time left: {Math.ceil(left/1000)}s

    } ``` --- ## State Management Patterns - **Local UI state**: `useState/useReducer` (forms, toggles). - **Derived state**: compute from source state; avoid duplicating. - **Global state**: only for cross‑cutting data (auth, theme). Use Context, Zustand, Redux Toolkit, or Jotai. - **Server state**: use **React Query/SWR** (caching, refetching, dedup). ```jsx // Server state example with React Query const { data, isLoading, error } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos }) ``` - **State machines**: XState/Zustand FSM for complex flows (explicit states, transitions). --- ## Data Fetching & Boundaries - **Suspense** for async UI boundaries (loading fallbacks). - **Error boundaries** for uncaught render errors. - **Skeletons** for perceived performance. - **Pagination/Infinite loading** to avoid large payloads. ```jsx // Error boundary (simplified) class ErrorBoundary extends React.Component { state = { hasError: false } static getDerivedStateFromError() { return { hasError: true } } render() { return this.state.hasError ?

    Something went wrong.

    : this.props.children } } ``` --- ## Styling Patterns - **Utility‑first**: Tailwind for consistency + speed. - **CSS Modules**: predictable scoping. - **CSS‑in‑JS** (MUI emotion/styled-components): dynamic styles, theming. - **Design tokens**: one source of truth for colors/spacing/typography. ```jsx // MUI theme tokens const theme = createTheme({ palette: { primary: { main: '#0d6efd' } }, shape: { borderRadius: 12 }, }) ``` --- ## Layout & Composition - **Page → Section → Component** hierarchy. - **Slot pattern** for flexible composition. ```jsx function Card({ header, children, footer }) { return (
    {header}
    {children}
    {footer}
    ) } ``` --- ## Performance Patterns - **Memoization**: `useMemo`, `useCallback`, `React.memo` for expensive work/props stability. - **Virtualization**: `react-window` for big lists. - **Code splitting**: dynamic imports to reduce initial JS. - **Avoid re‑renders**: key props, stable handlers, co-locate state. ```jsx const Chart = dynamic(() => import('./Chart'), { ssr: false }) ``` --- ## Architecture Patterns - **Atomic Design** (Atoms/Molecules/Organisms/Templates/Pages). - **Feature‑Sliced Design**: by domain (entities/features/shared). - **Monorepo packages** (PNPM/Turbo): share UI + utils. - **Micro‑frontends** (Module Federation): for very large orgs (use sparingly). --- ## Testing Patterns - **Unit**: pure functions/components (Jest/Vitest). - **Integration**: components with real children (React Testing Library). - **E2E**: user flows (Playwright/Cypress). Prefer testing **behavior**, not implementation details. ```jsx // RTL example render(