# @khanglvm/react > Shared state with rollback, typed translations and async events between React components. Install: `npm i @khanglvm/react`. Source: https://github.com/khanglvm/react. Synced from a local preview. --- # @khanglvm/react URL: https://docs.khangle.dev/react - Shared state with selectors, Immer updates and an undo function per update. - Typed translations: dictionaries checked by the compiler, translator hooks, and instant language switching without a page reload. - Async events between components that don't know each other, with typed answers. - Helpers for deep equality, cloning, stable references and React children. I built these to stop rewriting the same setup in every React project. The same designs run in production in two recruitment platforms, including a Next.js monorepo with more than ten feature packages. This package is their public, framework-neutral version. ## Pick a tool [#pick-a-tool] | You need to | Use | Guide | | --- | --- | --- | | Share editable state across a feature, with selectors and optimistic updates | `createContextState` | [State](state.md) | | Translate UI text with compile-time checks and switch language instantly | `defineLocale`, `createTranslatorHook` | [Translations](translation.md) | | Notify or ask mounted components elsewhere in the app and collect their answers | `createEventMethod` | [Events](events.md) | | Compare, clone or cache values; pick slots from `children` | `@khanglvm/react/helpers` | [Helpers](helpers.md) | | Know what runs in server and client components | | [Next.js App Router](nextjs.md) | The utilities also fit together: the translation guide keeps the current language in a `createContextState` store. Two small example apps run the same profile editor: typed translations with a language switcher, a store with an optimistic save that rolls back on failure, and an event that lets the editor veto a reset. - [React with Vite](https://github.com/khanglvm/react/tree/HEAD/examples/react-vite) - [Next.js App Router](https://github.com/khanglvm/react/tree/HEAD/examples/nextjs-app-router): language from a cookie, server-rendered text and metadata, server data seeding a client store. --- # Install URL: https://docs.khangle.dev/react/install ```sh npm install @khanglvm/react ``` The package ships ES modules with TypeScript declarations, and Immer is its only dependency. In Next.js App Router, files that use the hooks need `'use client'` at the top; the [Next.js guide](nextjs.md) lists what runs where. --- # Shared state with createContextState URL: https://docs.khangle.dev/react/state Use it for state that several components of one feature share: a form, an editor, a page's filters, the app shell (user, language, permissions). Keep state that one component owns in `useState`. Keep server cache concerns (refetching, retries, cache invalidation) in a data-fetching library; write its results into a store only when components edit them. The patterns below come from production React and Next.js apps. The [example apps](https://github.com/khanglvm/react/tree/master/examples) run the profile editor from this guide. ## 1. Quick start [#1-quick-start] ```tsx 'use client' // only needed in Next.js App Router import { createContextState } from '@khanglvm/react' const counter = createContextState<{ count: number }>() function Count() { const count = counter.useContextStateValue(state => state.count) return

Count: {count}

} function AddOne() { const setState = counter.useSetContextState() return } export default function App() { return ( ) } ``` Clicking the button rerenders `Count`. `AddOne` does not subscribe, so the store never rerenders it. ## 2. Create a store module [#2-create-a-store-module] Give each store its own file. Call the factory at module level, never inside a component, and rename the hooks after the feature so call sites read clearly. ```ts // profile/profile-store.ts 'use client' import { createContextState } from '@khanglvm/react' export type ProfileState = { profile: { id: string; name: string } draftName: string status: 'idle' | 'saving' | 'saved' | 'failed' } export const { Provider: ProfileProvider, useContextState: useProfileState, // [value, setState, getSnapshot] useContextStateValue: useProfileValue, // value only useSetContextState: useSetProfile, // setState only, no subscription useStateSnapshotGetter: useProfileSnapshot, // read without subscribing withContextProvider: withProfileProvider, } = createContextState('profile') ``` The optional argument (`'profile'`) is an instance ID. In the browser it keeps the same React context when a module is evaluated twice, for example after a hot reload or when two bundles load the same file. Use a distinct ID for each store, or leave it out. Keep types and plain helpers in a separate file if server components need them. In Next.js, everything exported from a `'use client'` file is a client reference, so a server component cannot call a helper function from it. ## 3. Read with selectors [#3-read-with-selectors] A selector picks what a component needs: ```tsx const name = useProfileValue(state => state.profile.name) const isSaving = useProfileValue(state => state.status === 'saving') const count = useProfileValue(state => state.items.filter(item => item.done).length) ``` A selector can return a new object or array. The store compares the result with the previous one by value (`deepEqual`) and keeps the previous reference when they match, so this does not rerender on every change: ```tsx const { name, status } = useProfileValue(state => ({ name: state.profile.name, status: state.status, })) ``` Without a selector, the hook returns the whole state, and the component rerenders on any change. Rules for selectors: - Keep them pure: the same state gives the same result, with no `Date.now()`, random values or side effects. In development builds (`process.env.NODE_ENV === 'development'`), `useContextStateValue` runs each selector twice and throws if the results differ. Vite, webpack and Next.js set that value in `dev` and replace it in production builds, so the check runs while you develop and is skipped in production builds. Node and test runners read `NODE_ENV` from the environment. - Treat the result as read-only. Change state through the setter. - Prefer small results. Comparing a large selected tree on every update costs time, and cyclic data is not supported. ## 4. Update state [#4-update-state] `setState` accepts a partial object or a draft function. ```tsx const setState = useSetProfile() // Partial object: replaces the listed top-level fields. setState({ status: 'saving' }) // Draft function: change nested data in place; Immer produces the next state. setState(draft => { draft.profile.name = 'Khang Le' draft.status = 'saved' }) ``` A partial object replaces each listed top-level field as a whole; it does not merge into nested objects. To change `profile.name` and keep `profile.id`, use a draft. Values passed in a partial object are deep-copied with [`deepClone`](helpers.md#deepclonevalue-cache). Keep state to plain data: objects, arrays, primitives, `Date`, `Map`, `Set`. An `Error`, a `Promise` or a `WeakMap` makes the copy throw `Unsupported type`, and a class instance becomes a plain object. Store `String(error)` rather than the error. Functions are kept by reference. The state is frozen from the moment the Provider mounts: `initialState` is deep-frozen in place, and every later state comes frozen from Immer. An object you put in the store, through `initialState` or a draft (an API response, a default constant), is frozen in place too, so other code that still holds it can no longer mutate it. Copy it first if something else changes it later. Like Immer, the freeze does not reach class instances, the keys and values inside a `Map` or `Set` (the collection itself is frozen), or the children of an object that was already frozen with `Object.freeze`. Edit those through the setter too. The state changes immediately, so the snapshot getter ([section 5](#5-read-the-latest-state-in-handlers)) sees it on the next line. Subscribers are notified once per microtask, so several `setState` calls in one handler cause one rerender pass. `useSetProfile()` does not subscribe the component to changes. Use it for buttons and handlers that write without reading. To read and write in one component, `useProfileState(selector)` returns `[value, setState, getSnapshot]`: ```tsx const [draftName, setState] = useProfileState(state => state.draftName) setState({ draftName: e.target.value })} /> ``` ## 5. Read the latest state in handlers [#5-read-the-latest-state-in-handlers] A value from render can be stale in an async handler. `useProfileSnapshot()` returns a getter that reads the current state when called, without subscribing: ```tsx const getSnapshot = useProfileSnapshot() async function save() { const { profile, draftName } = getSnapshot() // or with a selector: getSnapshot(state => state.draftName) await api.saveName(profile.id, draftName) } ``` Use it to guard duplicate requests too: ```tsx async function loadMore() { if (getSnapshot(state => state.isLoading)) return // ... } ``` The snapshot is the store's current object, not a copy, so reading it costs nothing and its references stay stable between reads. Because the state is frozen (section 4), changing it throws a `TypeError` instead of silently skipping the subscribers. To get an editable copy, use `deepClone(getSnapshot())` or `structuredClone`, then write changes back with `setState`. ## 6. Seed the store with data [#6-seed-the-store-with-data] `initialState` is read once, when the Provider mounts. Later changes to the prop do not reset the store, so edits in progress survive parent rerenders. React (client-side data): mount the Provider when the data is ready. ```tsx function ProfilePage() { const [profile, setProfile] = useState(null) useEffect(() => { getProfile().then(setProfile) }, []) if (!profile) return return ( ) } ``` Next.js App Router: fetch in a server component and pass serializable data to the Provider. ```tsx // app/profile/page.tsx (server component) import { ProfileProvider } from '@/profile/profile-store' import { profileStateFrom } from '@/profile/profile' // plain module, not 'use client' export default async function Page() { const profile = await getProfile() return ( ) } ``` Give the Provider a complete initial state. `initialState` is typed as `Partial`, but selectors read fields that must exist. To start over with fresh data, remount the Provider, for example with `key={profile.id}`. ## 7. Optimistic updates with revert [#7-optimistic-updates-with-revert] Every `setState` returns a function that undoes that update. Show the change immediately, then undo it if the request fails: ```tsx async function save() { const { profile, draftName } = getSnapshot() const revert = setState(draft => { draft.profile.name = draftName draft.status = 'saving' }) try { await api.saveName(profile.id, draftName) setState({ status: 'saved' }) } catch { revert() // profile.name and status return to their values before this update setState({ status: 'failed' }) } } ``` The revert applies Immer's inverse patches for that one update to the current state: - Fields changed only by other updates keep their new values. - A field changed by this update and then changed again is set back to the value before this update, overwriting the later change. - Revert functions are independent. There is no history stack or redo. If two saves can overlap on the same field, queue them or disable the button while one is pending. Pass `false` to skip recording patches when you never revert. The returned function then does nothing: ```tsx const setState = useSetProfile(false) const [value, setFast] = useProfileState(selector, false) ``` ## 8. Load data into the store [#8-load-data-into-the-store] Stores can hold fetched data next to the UI state that edits it. Keep loading flags in the store too: ```tsx async function loadNotifications(page: number) { if (getSnapshot(state => state.isLoading)) return // already loading setState({ isLoading: true }) try { const result = await api.notifications(page) setState(draft => { draft.items.push(...result.items) draft.page = page draft.isLoading = false }) } catch (error) { setState({ isLoading: false, error: String(error) }) } } ``` If you already use React Query, SWR or Apollo, let it own server data and caching, and use a store for the editable copy or the UI state around it. ## 9. Wrap the store in feature hooks [#9-wrap-the-store-in-feature-hooks] Export hooks that describe the feature instead of exposing selectors everywhere. Components then depend on intent, and you can change the state shape in one place. ```ts export function useUnreadCount() { return useNotificationValue(state => state.items.filter(item => !item.read).length) } export function useNotificationActions() { const setState = useSetNotifications(false) return useMemo(() => ({ markRead(id: string) { setState(draft => { const item = draft.items.find(entry => entry.id === id) if (item) item.read = true }) }, clear() { setState({ items: [] }) }, }), [setState]) } ``` The setter is stable for the life of the Provider, so `useMemo` keeps the actions object stable too. ## 10. Scope, nesting and several stores [#10-scope-nesting-and-several-stores] Each Provider owns separate state. Where you place it decides who shares it: - App-wide state (user, language, permissions): one Provider in the root layout. - A page or flow: a Provider in that route's layout, so the state survives navigation between its child routes. - Per instance: a Provider inside a repeated component, so each card or dialog has its own state. Providers of different stores nest freely. A component reads each store through its own hooks: ```tsx ``` When a handler in an inner feature needs a value from an outer store, read it with the outer store's snapshot getter instead of subscribing. A component outside its matching Provider gets an empty fallback store: selectors read `{}` and setters do nothing. The package raises no missing-Provider error, but a selector that reads a nested field, such as `state => state.profile.name`, throws a `TypeError`. Development builds log a one-time warning per store. If an update seems to vanish, check that the component sits under the Provider created by the same factory call. ## 11. Wrap a component with its Provider [#11-wrap-a-component-with-its-provider] `withContextProvider` returns a component that renders its own Provider, with initial state derived from props: ```tsx type ProfileCardProps = { profile: Profile } export const ProfileCard = withProfileProvider( function ProfileCardView() { const name = useProfileValue(state => state.profile.name) return

{name}

}, { initialState: props => ({ profile: props.profile, draftName: props.profile.name, status: 'idle' }), }, ) // , each instance with its own store ``` The type parameter describes the component's props, not the store. An optional `bindPropToState(draft, props)` copies props into the store when a prop value changes after mount. Props are compared key by key with `Object.is`, so a parent rerender with the same values does nothing. When a value does change, the callback overwrites the fields it writes, including local edits to them. Inline functions, JSX `children` and inline objects or arrays are new values on every render, so they count as changes: memoize them with `useCallback`/`useMemo`, or keep them out of the wrapped component's props. `StateSynchronizer` exposes the same mechanism as a component that you render under an existing Provider. It compares its `data` prop the same way: an inline object of primitive values is fine, while a `Date`, `Map`, `Set` or class instance compares by reference. ```tsx { draft.draftName = data.name }} /> ``` Both are experimental. Prefer seeding with `initialState` and writing from event handlers. ## 12. Compute derived data once per batch [#12-compute-derived-data-once-per-batch] When many updates in a row invalidate an expensive derived value, register a post-flush callback. It runs once per microtask batch, after all updates and before subscribers are notified, and it receives an Immer draft: ```tsx function HierarchyRegistrar() { const setPostFlush = useSetBuilderPostFlush() useEffect(() => { setPostFlush(draft => { if (!draft.hierarchyStale) return draft.hierarchy = buildHierarchy(draft.blocks) draft.hierarchyStale = false }) }, [setPostFlush]) return null } // Updates only mark the value stale: setState(draft => { draft.blocks.push(block) draft.hierarchyStale = true }) ``` Render the registrar once inside the Provider. Each Provider holds one callback; registering again replaces it, and there is no unregister function. Changes made by the callback are not part of any revert. ## 13. Server rendering and Next.js [#13-server-rendering-and-nextjs] - The package entry for this utility already carries `'use client'`. Add `'use client'` to your files that call `createContextState` (server components import their Provider from them) and to every component that calls the hooks. - Server components can render the Provider and pass `initialState`, as in section 6. The data must be serializable. - Each Provider creates its own store during server rendering. Two requests never share state, even with the same instance ID. - Pass the same initial values on the server and on the client so hydration matches. - Selected snapshots are cached per hook, so finished server renders release them without effect cleanup. See the [Next.js guide](nextjs.md) for where each piece of the package runs. ## 14. How it works and what to watch for [#14-how-it-works-and-what-to-watch-for] The Provider keeps the state in a ref and a set of subscribers. Hooks subscribe through `useSyncExternalStore`. On a change, every subscriber of that Provider runs its selector; a component rerenders only if its selected value differs by `deepEqual` from the previous one. This is selector-level filtering, not field-level dependency tracking, so many subscribers with heavy selectors still cost work on each update. Checklist: - Call `createContextState` at module level. - Provide every field in `initialState`. - Keep selectors pure and their results small. - Use drafts for nested updates; partial objects replace top-level fields. - Use the snapshot getter, not render values, inside async code. - Treat snapshots and selected values as read-only; they are frozen. Copy before editing. - Remount the Provider (`key`) to reset it; changing `initialState` does nothing after mount. - Check Provider placement when updates seem to do nothing. ## 15. API reference [#15-api-reference] `createContextState(instanceId?)` returns: | Export | Signature | Notes | | --- | --- | --- | | `Provider` | `}>` | Reads `initialState` once on mount | | `useContextState` | `(selector?, enableRevert = true) => [value, setState, getSnapshot]` | Subscribes | | `useContextStateValue` | `(selector?) => value` | Subscribes; dev purity check | | `useSetContextState` | `(enableRevert = true) => setState` | No subscription | | `useStateSnapshotGetter` | `() => getSnapshot` | No subscription | | `useSetPostFlush` | `() => (callback: (draft) => void) => void` | One callback per Provider | | `withContextProvider` | `(Component, { initialState?, bindPropToState? })` | Wraps in a Provider; forwards refs | | `StateSynchronizer` | `` | Experimental | | `withStateProvider` | Same as `withContextProvider` | Deprecated name | - `setState(partialOrDraftFn) => revert`: `revert()` undoes that update; with `enableRevert = false` it does nothing. - `getSnapshot(selector?)`: returns the current state, or the selector's result. `createStateManager(instanceId?)` wraps the same store and adds older names: `useState`, `useStateValue`, `useSetState`, `useSnapshot`, `withProvider`. Use `createContextState` in new code. Type helpers: `TContextState` and `TStateManager` are the return types of the two factories. --- # Typed translations URL: https://docs.khangle.dev/react/translation ```ts const text = assertTranslation({ save: { en: 'Save', vi: 'Lưu' }, }) // In a component: const { t, d } = useTranslator() t(d.save) // "Save" or "Lưu", depending on the current language ``` Use it when your app ships a known, small set of languages and you want the dictionaries checked by the compiler. It does not detect the browser language, handle plural rules, or format dates and numbers. Use `Intl` for formatting, or a fuller i18n library if you need plurals, ICU messages, or translation files loaded at runtime. The complete code from this guide runs in two example apps: [React with Vite](https://github.com/khanglvm/react/tree/master/examples/react-vite) and [Next.js App Router](https://github.com/khanglvm/react/tree/master/examples/nextjs-app-router). ## 1. Translate one string [#1-translate-one-string] `createTranslator(language)` returns a function `t` that picks that language's text from an entry. It works anywhere: React, Node, a server component, a test. ```ts import { createTranslator } from '@khanglvm/react' const t = createTranslator<'en' | 'vi'>('vi') t({ en: 'Save', vi: 'Lưu' }) // "Lưu" t({ en: 'Hello, {name}!', vi: 'Xin chào, {name}!' }, { '{name}': 'Khang' }) // "Xin chào, Khang!" ``` The second argument replaces text; [section 7](#7-insert-values-into-text) explains the rules. ## 2. Declare your languages once [#2-declare-your-languages-once] Create one module that owns the language list. Bind it with `defineLocale` so every dictionary and hook uses the same union type. ```ts // i18n/locale.ts import { defineLocale } from '@khanglvm/react' export const LANGUAGES = ['en', 'vi'] as const export type Language = (typeof LANGUAGES)[number] // 'en' | 'vi' export const DEFAULT_LANGUAGE: Language = 'en' // Runtime type guard for values from cookies, headers, URLs or storage. export function isLanguage(value: unknown): value is Language { return typeof value === 'string' && (LANGUAGES as readonly string[]).includes(value) } export const { assertTranslation, createTranslator, createTranslatorHook } = defineLocale() ``` Two kinds of checking come from this file: - At compile time, `assertTranslation` checks that every entry has every language in `Language`. - At run time, `isLanguage` narrows an untrusted string, such as a cookie value, to `Language` before you store it. This module has no client-only code, so Next.js server components can import it too. To add a language later, add it to `LANGUAGES`. TypeScript then lists every entry that still lacks it. ## 3. Write dictionaries [#3-write-dictionaries] Wrap each dictionary in `assertTranslation`. A leaf is an object with one string per language. Any other object is a namespace, and namespaces can nest to any depth. ```ts // i18n/dictionary.ts import { assertTranslation } from './locale' export const translation = assertTranslation({ common: { appName: { en: 'Team settings', vi: 'Cài đặt nhóm' }, language: { en: 'Language', vi: 'Ngôn ngữ' }, }, profile: { greeting: { en: 'Hello, {name}!', vi: 'Xin chào, {name}!' }, nameLabel: { en: 'Display name', vi: 'Tên hiển thị' }, save: { en: 'Save', vi: 'Lưu' }, }, }) ``` What TypeScript does with it: | You write | Result | | --- | --- | | `save: { en: 'Save' }` | Error: `vi` is missing | | `save: { en: 'Save', vi: 'Lưu' }` | OK | | `translation.profile.nope` | Error: property `nope` does not exist | | `translation.profile.` in your editor | Autocomplete lists `greeting`, `nameLabel`, `save` | | `t(translation.profile)` | Error: `t` only accepts a leaf, not a namespace | | `translation.profile.save.en = 'x'` | Error: the returned type is deeply readonly | `assertTranslation` only changes types. At run time it returns the same object, unfrozen and unvalidated, so data from outside your code (a CMS, an API) gets no check from it. Dictionaries can live in several files. Wrap each one, then combine them into the object you pass to the hooks: ```ts // features/billing/text.ts export const billingText = assertTranslation({ invoice: { en: 'Invoice', vi: 'Hóa đơn' }, }) // i18n/dictionary.ts export const translation = assertTranslation({ common: commonText, billing: billingText, }) ``` ## 4. Hold the current language in a store [#4-hold-the-current-language-in-a-store] The translator hooks do not store the language. You pass them a hook that returns it, so the language can live wherever your app keeps shared state. A [`createContextState`](state.md) store is a good fit: changing the value rerenders exactly the components that read it. ```tsx // i18n/language-store.tsx 'use client' // needed in Next.js; harmless elsewhere import { useCallback } from 'react' import { createContextState } from '@khanglvm/react' import type { Language } from './locale' export const { Provider: LanguageProvider, useContextStateValue: useLanguageState, useSetContextState: useSetLanguageState, useStateSnapshotGetter: useLanguageSnapshot, } = createContextState<{ language: Language }>('app-language') export function useLanguage() { return useLanguageState(state => state.language) } export function useSetLanguage() { const setState = useSetLanguageState(false) // false: no undo history needed return useCallback((language: Language) => { setState({ language }) document.documentElement.lang = language // Also save the choice. Where depends on the framework (sections 8 and 9). }, [setState]) } ``` Switching is instant: `setLanguage('vi')` writes one field. Every translator hook reads that field through `useLanguage`, so React rerenders those components with Vietnamese text. Nothing is fetched or reloaded, and the rest of your state (form input, scroll position, open dialogs) is untouched. ## 5. Create translator hooks [#5-create-translator-hooks] Pass the dictionary and your language hook to `createTranslatorHook`. Export the hooks your components will use. ```ts // i18n/translator.ts 'use client' import { createTranslatorHook } from './locale' import { translation } from './dictionary' import { useLanguage } from './language-store' export const { useTranslator, createNamespacedTranslatorHook } = createTranslatorHook({ translation, usePreferredLanguage: useLanguage, }) // One hook per feature. `d` is already narrowed to that namespace. export const useCommonText = createNamespacedTranslatorHook('common') export const useProfileText = createNamespacedTranslatorHook('profile') ``` Every hook returns `{ t, d, language }`: - `t(entry, replacements?)` returns the entry's text in the current language. - `d` is the dictionary, or the part you selected, typed for autocomplete. - `language` is the current language. `useTranslator` accepts several shapes. Each one changes only what `d` contains; the whole dictionary is always in the bundle. | Call | `d` is | | --- | --- | | `useTranslator()` | The whole dictionary: `d.profile.save` | | `useTranslator('profile')` | That namespace: `d.save` | | `useTranslator('common', 'profile')` | An object with both: `d.common.appName`, `d.profile.save` | | `useTranslator(['common', 'profile'])` | The same, from an array | | `useTranslator(dict => dict.profile)` | Whatever your selector returns | | `useProfileText()` (from `createNamespacedTranslatorHook('profile')`) | That namespace: `d.save` | A string returns the namespace itself. An array always returns an object keyed by namespace, even with one item: `useTranslator(['profile'])` gives `d.profile.save`. ## 6. Use the hooks in components [#6-use-the-hooks-in-components] ```tsx 'use client' import { useProfileText } from '@/i18n/translator' export function SaveButton() { const { t, d } = useProfileText() return } ``` A language switcher reads `language` from the same hook and calls `useSetLanguage`: ```tsx 'use client' import { LANGUAGES } from '@/i18n/locale' import { useSetLanguage } from '@/i18n/language-store' import { useCommonText } from '@/i18n/translator' export function LanguageSwitcher() { const { t, d, language } = useCommonText() const setLanguage = useSetLanguage() return ( ) } ``` ## 7. Insert values into text [#7-insert-values-into-text] The second argument of `t` maps text to replace to its value: ```ts // dictionary: greeting: { en: 'Hello, {name}!', vi: 'Xin chào, {name}!' } t(d.greeting, { '{name}': user.name }) // "Hello, Khang!" ``` Each key is the exact text to find. Matching ignores case and replaces every occurrence; where keys overlap, the longest one wins. There is no placeholder syntax, which leads to these rules: - Include the braces in the key. `{ name: 'Khang' }` replaces only the word, leaving `Hello, {Khang}!`. - Choose tokens that appear nowhere else in the text. A bare token like `count` also matches inside `discount`. - Any characters work in keys, matched as written: `{0}`, `$total` and `%s` are all fine. - The token in each language must be the same text. TypeScript does not check tokens. ## 8. Set up a React app (Vite) [#8-set-up-a-react-app-vite] In a client-only app, read the saved language once at startup and pass it to the Provider. Save each change to `localStorage`. ```tsx // i18n/language-store.tsx (additions) import { DEFAULT_LANGUAGE, isLanguage, type Language } from './locale' export function getInitialLanguage(): Language { const saved = localStorage.getItem('lang') if (isLanguage(saved)) return saved const browser = navigator.language.slice(0, 2) return isLanguage(browser) ? browser : DEFAULT_LANGUAGE } // Inside useSetLanguage's callback: localStorage.setItem('lang', language) ``` ```tsx // main.tsx import { createRoot } from 'react-dom/client' import { App } from './App' import { LanguageProvider, getInitialLanguage } from './i18n/language-store' createRoot(document.getElementById('root')!).render( , ) ``` The `'use client'` lines from the earlier sections do nothing in Vite, so you can keep or remove them. Full app: [examples/react-vite](https://github.com/khanglvm/react/tree/master/examples/react-vite). ## 9. Set up a Next.js App Router app [#9-set-up-a-nextjs-app-router-app] The server needs the language before it renders, so keep it in a cookie. The flow: 1. The root layout (a server component) reads the cookie and seeds `LanguageProvider`. Server and client start from the same value, so hydration matches. 2. Client components translate with the hooks from section 5. 3. Server components, `generateMetadata` and route handlers translate with `createTranslator`, using the language from the same cookie. 4. Switching writes the store and the cookie. Client components change at once. `router.refresh()` then re-renders server components with the new cookie and keeps client state. ### Read the language on the server [#read-the-language-on-the-server] ```ts // i18n/server.ts import { cookies } from 'next/headers' import { DEFAULT_LANGUAGE, createTranslator, isLanguage } from './locale' import { translation } from './dictionary' export async function getRequestLanguage() { const value = (await cookies()).get('lang')?.value return isLanguage(value) ? value : DEFAULT_LANGUAGE } export async function getServerTranslator() { const language = await getRequestLanguage() return { t: createTranslator(language), d: translation, language } } ``` Import this file only from server code; `next/headers` fails in client components. ### Seed the Provider in the root layout [#seed-the-provider-in-the-root-layout] ```tsx // app/layout.tsx (server component) import type { Metadata } from 'next' import type { ReactNode } from 'react' import { LanguageProvider } from '@/i18n/language-store' import { getRequestLanguage, getServerTranslator } from '@/i18n/server' export async function generateMetadata(): Promise { const { t, d } = await getServerTranslator() return { title: t(d.common.appName) } } export default async function RootLayout({ children }: { children: ReactNode }) { const language = await getRequestLanguage() return ( {children} ) } ``` ### Save the choice and refresh server text [#save-the-choice-and-refresh-server-text] ```tsx // i18n/language-store.tsx: inside useSetLanguage's callback document.cookie = `lang=${language}; path=/; max-age=31536000; samesite=lax` ``` ```tsx // LanguageSwitcher: after setLanguage(next) const router = useRouter() // from 'next/navigation' router.refresh() ``` Skip `router.refresh()` if every translated string on the page comes from client components. Then the switch never touches the server. ### Translate in a server component [#translate-in-a-server-component] ```tsx // app/page.tsx (server component) import { getServerTranslator } from '@/i18n/server' import { LanguageSwitcher } from '@/components/LanguageSwitcher' export default async function Page() { const { t, d } = await getServerTranslator() return (

{t(d.common.appName)}

) } ``` Server components can import `createTranslator` and `defineLocale` from `@khanglvm/react`, and use the `assertTranslation` that `defineLocale` returns; the package's translator module has no `'use client'` directive. They cannot call the hooks. The state and event modules are client modules, so the files that call `createContextState` and `createTranslatorHook` start with `'use client'`. If your URLs carry the language (`/en/...`, `/vi/...`), read it from the route params instead of the cookie. To switch without a navigation, update the store and replace the URL with `window.history.replaceState`, which Next.js 14.1 and later keep in sync with its router. Full app, including `generateMetadata` and a server-rendered line that updates after the switch: [examples/nextjs-app-router](https://github.com/khanglvm/react/tree/master/examples/nextjs-app-router). The [Next.js guide](nextjs.md) covers `'use client'` boundaries for all utilities. ## 10. Translate outside components [#10-translate-outside-components] The hooks run only in components. For other code, pass the translator in or create one from a known language. Validation rules, table columns and other values built from text: build them in the component and pass `t` and `d` to a plain function. The hook creates a new `t` on every render, so memoize on `language`: ```tsx import { useMemo } from 'react' import type { LocalizedString } from '@khanglvm/react' import type { Language } from '@/i18n/locale' type Translate = (entry: LocalizedString, replacements?: Record) => string function buildNameRules(t: Translate, d: typeof formText) { return { required: t(d.nameRequired) } } function NameField() { const { t, d, language } = useFormText() const rules = useMemo(() => buildNameRules(t, d), [language]) // ... } ``` Event handlers and async code: read the language when the code runs, then call `createTranslator`. A `t` captured during an earlier render keeps the language of that render. ```tsx const getLanguage = useLanguageSnapshot() // exported by the store in section 4 async function onSave() { await save() const t = createTranslator(getLanguage(state => state.language)) showToast(t(d.saved)) } ``` Constants: keep translatable constants as entries and translate them where they are shown. ```ts export const ERROR_TEXT = assertTranslation({ offline: { en: 'You are offline', vi: 'Không có kết nối mạng' }, }) ``` ## 11. Organize a large app [#11-organize-a-large-app] This layout comes from a production Next.js monorepo with more than ten feature packages, all sharing one language store: - One `locale.ts` for the whole app, imported by every feature. - One language store in the app shell, seeded in the root layout. - Each feature owns its dictionaries: one file per screen or area, combined in the feature's `translation.ts`. - Each feature exports its own hook from `createTranslatorHook`, passing the shared `useLanguage`. Components import only their feature's hook, so autocomplete shows only that feature's keys. - Small components can keep a `text.ts` next to them and create a namespaced hook from it. - Server code uses one helper built on `createTranslator`, like `getServerTranslator()` in section 9. The monorepo's version also takes a namespace and returns only that part of `d`. Because every feature hook reads the same store, one `setLanguage` call switches the whole app at once. ## 12. Limits [#12-limits] - All languages ship in the bundle. Selecting a namespace narrows `d`; it does not split code or load files. - A language missing at run time returns `''`. This can only happen with data that skipped `assertTranslation`, or with an unchecked cast. - No plurals, gender, ICU syntax, date or number formatting. Combine with `Intl` (`new Intl.NumberFormat(language)`), using `language` from the hook. - `t` is a new function on every render; depend on `language` in `useMemo` and `useEffect`. - `assertTranslation` checks shape only. It does not freeze objects, check token names, or compare text across languages. ## 13. API reference [#13-api-reference] ### `defineLocale()` [#definelocalelanguages] Binds a string union and returns `{ assertTranslation, createTranslator, createTranslatorHook }`. Call it once in `locale.ts`. Safe on the server. ### `assertTranslation(dictionary)` [#asserttranslationdictionary] Returns `dictionary` unchanged, typed as `TDeepReadonly`. Compile error if a leaf lacks a language. ### `createTranslator(language)` [#createtranslatorlanguage] Returns `t(entry, replacements?) => string`. Available from the package root and from `defineLocale()`. Safe on the server. ### `createTranslatorHook({ translation, usePreferredLanguage })` [#createtranslatorhook-translation-usepreferredlanguage-] - `translation`: the combined dictionary. - `usePreferredLanguage`: a hook returning the current language. It is called inside every translator hook, so it must follow the rules of hooks. Returns: - `useTranslator(selection?)`: see the table in section 5. Returns `{ t, d, language }`. - `createNamespacedTranslatorHook(namespace)`: returns a hook with no arguments that returns `{ t, d, language }` for that namespace. ### Types [#types] - `LocalizedString`: one leaf, `{ [language]: string }`. - `TranslationNamespace`: a nested object of leaves and namespaces. --- # Async events between components URL: https://docs.khangle.dev/react/events ```ts const answers = await emitEvent('profile:before-reset', { source: 'header' }) if (answers.some(answer => answer?.allow === false)) return // a mounted editor said no ``` Prefer a callback prop for parent and child, and a [store](state.md) for data that components render. Events suit commands ("open the dialog"), facts ("the profile changed, refetch") and questions to whoever is mounted ("may I leave?"). ## 1. Define the events [#1-define-the-events] Describe each event in one type. A value type is a notification, and a function type is a request whose return type is the listener's answer. ```ts // profile/events.ts 'use client' import { createEventMethod } from '@khanglvm/react' type ProfileEvents = { // Notification with data 'profile:reset': { by: string } // Notification without data 'profile:open-editor': undefined // Request: listeners receive the data and answer with { allow } 'profile:before-reset': (data: { source: string }) => { allow: boolean } // Request without input 'profile:has-unsaved': () => boolean // Request with an async answer 'profile:collect-drafts': (data: { formId: string }) => Promise } export const { useEventListener: useProfileEvent, emitEvent: emitProfileEvent, } = createEventMethod() ``` Event names are global across the page: two factories that both define `'saved'` reach each other's listeners. Prefix names with the feature (`profile:`, `chat:`). A request without input is a function with no parameters, such as `() => boolean`. ## 2. Listen [#2-listen] Call the hook in a component. It registers after mount and removes the listener on unmount. ```tsx function ProfileForm() { const getSnapshot = useProfileSnapshot() useProfileEvent('profile:reset', ({ by }) => { console.log(`reset by ${by}`) }) useProfileEvent('profile:before-reset', () => { const { draftName, profile } = getSnapshot() return { allow: draftName === profile.name || window.confirm('Discard your changes?') } }) // ... } ``` The handler can change between renders; the hook always calls the latest one, so it sees current props. Read store state through the store's snapshot getter ([state guide, section 5](state.md#5-read-the-latest-state-in-handlers)) so async handlers see current values too. ## 3. Emit a notification [#3-emit-a-notification] Call `emitEvent` from an event handler or an effect. The data argument is required when the event has data, and absent when the type is `undefined`. ```tsx await emitProfileEvent('profile:reset', { by: 'header' }) await emitProfileEvent('profile:open-editor') ``` The returned promise resolves after every listener finishes; awaiting it is optional for notifications. ## 4. Ask mounted components and collect answers [#4-ask-mounted-components-and-collect-answers] For a function-typed event, `emitEvent` resolves to an array with one entry per listener that answered. Nobody mounted means an empty array. ```tsx async function reset() { const answers = await emitProfileEvent('profile:before-reset', { source: 'header' }) // A veto: any mounted listener can block. No listeners means no objection. if (answers.some(answer => answer?.allow === false)) return setState({ draftName: savedName, status: 'idle' }) await emitProfileEvent('profile:reset', { by: 'header' }) } ``` Listeners run concurrently. The array keeps the order in which listeners registered, not the order in which they finished. Check answers defensively (`answer?.allow`), for the reasons in [section 7](#7-errors-and-results). ## 5. More patterns [#5-more-patterns] These come from a production app with events shared across feature packages. **Guard before a risky action.** Before switching the account or workspace, the shell emits `shell:before-switch`. Every mounted form with unsaved changes answers `{ canSwitch: false }` after asking the user, and the switch stops. **Refresh after a change.** After the switch succeeds, the shell emits `account:changed`. Each mounted screen listens and refetches its own data, so the shell does not need to know which screens exist. **Commands to a component that owns the UI.** A deep leaf button emits `dialog:open-upgrade` with the data the dialog needs. The shell owns the dialog and its state, and the leaf does not import it. **Let each instance decide.** When several instances listen, each one ignores events meant for another: ```tsx useBuilderEvent('builder:open-settings', ({ blockId }) => { if (!hasBlock(blockId)) return // not mine openSettings(blockId) }) ``` **One listener as a service.** A single component listens to `tracking:capture` and sends analytics; anything in the app can emit it without importing the analytics client. ## 6. Cancel work with the abort signal [#6-cancel-work-with-the-abort-signal] Every handler receives an `AbortSignal` as its second argument. When the listening component unmounts, the hook aborts it. Pass it to anything you can cancel: ```tsx useProfileEvent('profile:collect-drafts', async ({ formId }, signal) => { const response = await fetch(`/api/drafts/${formId}`, { signal }) return response.json() }) ``` Each call creates a new signal, and the hook keeps only the latest. Unmounting aborts the latest call; earlier calls that are still running are not aborted. Events without data work the same way: the first argument is `undefined` and the signal comes second. ```tsx useProfileEvent('profile:has-unsaved', (_data, signal) => checkDrafts({ signal })) ``` ## 7. Errors and results [#7-errors-and-results] - A listener that throws or rejects is logged with `console.error` and left out of the results. The array can be shorter than the number of listeners. - A listener that throws an `AbortError` counts as an answer of `undefined`. - A listener that returns nothing contributes `undefined`. - `emitEvent` itself does not reject because of a listener. The TypeScript type promises an answer from every listener, but an entry can be `undefined` or missing. Use optional chaining or a type check before acting on one. Notification events are typed to resolve to `void`. At run time they also resolve to an array of whatever listeners returned. ## 8. Next.js and server rendering [#8-nextjs-and-server-rendering] The module is a client module. Listeners register in an effect, so nothing runs during server rendering. Call `emitEvent` only in the browser, from event handlers or effects: it reads `window`, so on the server its promise rejects with a `ReferenceError`. ## 9. Limits [#9-limits] - Only mounted listeners receive an event. There is no queue, replay or delivery guarantee for components that mount later. - One page-wide registry (`window.__LVMK_EVENT_LISTENER__`). Names are not isolated per factory. - Not a cross-tab or server event bus. ## 10. API reference [#10-api-reference] `createEventMethod()` returns: - `useEventListener(name, handler)`: a hook. The handler is called as `handler(data, signal)`; `data` is `undefined` for events without it. The return value of `handler` is the answer for function-typed events. - `emitEvent(name, data?)`: returns a `Promise`. For function-typed events it resolves to an array of answers; for notifications, to `void` in the types. --- # Next.js App Router URL: https://docs.khangle.dev/react/nextjs ## What runs where [#what-runs-where] | Import | Server components, `generateMetadata`, route handlers | Client components | | --- | --- | --- | | `createTranslator`, `defineLocale`, and the `assertTranslation` it returns | Yes | Yes | | Hooks from `createTranslatorHook` | No (hooks) | Yes | | `createContextState` and its hooks | Render the `Provider` and pass `initialState` only | Yes | | `createEventMethod` | No | Yes; emit from handlers or effects | | `@khanglvm/react/helpers` | Yes | Yes | The package marks its state and event modules with `'use client'`, and leaves the translator and helpers without it. Importing everything from the root `@khanglvm/react` is fine on both sides. ## Rules for your own files [#rules-for-your-own-files] 1. Files that call `createContextState`, `createTranslatorHook` or `createEventMethod` start with `'use client'`. 2. Keep types, constants, dictionaries and plain helpers in files without `'use client'`. Every export of a client file is a client reference on the server: a server component can render a client component from it but cannot call its functions. For example, keep `profileStateFrom(profile)` in `profile/profile.ts`, not in the store file. 3. Server-only helpers that use `next/headers` (cookies, headers) live in their own file and are imported only by server code. A layout that follows these rules: ```text i18n/ locale.ts # languages, isLanguage, defineLocale: server + client dictionary.ts # assertTranslation dictionaries: server + client server.ts # cookies() -> language, getServerTranslator: server only language-store.tsx # 'use client': language store, useLanguage, useSetLanguage translator.ts # 'use client': translator hooks profile/ profile.ts # types and helpers: server + client profile-store.ts # 'use client': createContextState events.ts # 'use client': createEventMethod app/ layout.tsx # server: reads the cookie, renders LanguageProvider page.tsx # server: fetches data, renders ProfileProvider ``` ## Seed stores from the server [#seed-stores-from-the-server] A server component can fetch data and pass it to a Provider. The store keeps it as initial state, and all later changes happen on the client. ```tsx // app/page.tsx export default async function Page() { const profile = await getProfile() return ( ) } ``` - Pass serializable data: plain objects, arrays, strings, numbers, booleans, `null`. - The Provider reads `initialState` once. A later `router.refresh()` re-renders the server component with new props, and the mounted store ignores them, so edits survive. Use `key` to remount when you want the new data. - Put app-wide Providers in `app/layout.tsx` and route-group Providers in the group's `layout.tsx`. Layout state survives navigation between child routes. ## Language switching without a reload [#language-switching-without-a-reload] The [translation guide](translation.md#9-set-up-a-nextjs-app-router-app) has the full setup. In short: the root layout reads a `lang` cookie and seeds the language store; client components translate through hooks and switch as soon as the store changes; server components translate with `createTranslator` and pick up the change after `router.refresh()`. ## Events [#events] Listeners register in effects, so they never run on the server. Emit from event handlers or effects; `emitEvent` reads `window`, so on the server its promise rejects. ## Troubleshooting [#troubleshooting] | Symptom | Likely cause | | --- | --- | | "Attempted to call ...() from the server but ... is on the client" | A server component called a function exported from a `'use client'` file; move the function to a plain module | | `useContext` or hook errors in a server component | A hook from this package was called on the server; move that code to a client component | | Hydration mismatch on translated text | Server and client chose different languages; read the same cookie on the server and seed the Provider with it | | Server-rendered text stays in the old language | Call `router.refresh()` after switching, or render that text in a client component | | An update does nothing | The component is outside the Provider of that store, so it got the no-op fallback store | --- # Helpers and utility types URL: https://docs.khangle.dev/react/helpers ## Copying, comparison, and caching [#copying-comparison-and-caching] ### deepClone(value, cache?) [#deepclonevalue-cache] Use this when copying a nested value with the same rules the state utility uses for partial updates. It handles cycles, arrays, plain objects, Date, RegExp, Map, Set, ArrayBuffer and typed arrays. Functions, AbortSignal, and FormData are retained by reference. An optional WeakMap tracks copies during recursion. Any other object type throws `Unsupported type`, including Error, Promise, WeakMap, WeakSet, URL and Blob. A class instance is copied as a plain object, so its methods and prototype are lost. Own JSON keys such as `__proto__` are copied as data properties without changing the clone's prototype. ```ts import { deepClone } from '@khanglvm/react/helpers' const original = { tags: ['react'], createdAt: new Date('2026-01-01') } const copy = deepClone(original) copy.tags.push('typescript') // original.tags is unchanged ``` An object spread only copies one level; this function descends into nested data. A typical use is handing out a copy of live state, such as an export snapshot, that the caller can change without touching the store. For standard structured-clone-compatible data, consider the platform's `structuredClone` first. This helper is not a universal clone: it drops custom object prototypes and symbol properties, and typed-array views are rebuilt from their entire backing buffer without preserving their original offset or length. It also expects AbortSignal and FormData globals to exist. ### deepEqual(a, b) [#deepequala-b] Use this for value comparison of acyclic objects, arrays, Maps, and Sets when reference equality is insufficient. It also compares Date timestamps, RegExp strings, constructors, and NaN; React element `_owner` fields are skipped. Typical uses: skip copying a prop into local state when the new prop has a new reference but the same content, and return the previous object from an immutable update when nothing changed, so memoized consumers keep their reference. ```ts import { deepEqual } from '@khanglvm/react/helpers' deepEqual({ tags: ['react'] }, { tags: ['react'] }) // true ``` Maps compare their size, keys, and values. Keys use native Map identity, and values are compared recursively. Sets compare size and membership using native Set identity. Insertion order does not matter. Object keys and Set members must be the same references; matching object contents alone are insufficient. There is no cycle detection. Symbol and non-enumerable properties are not included. Use a comparator designed for those cases when they are part of your data. ### createCacheStorage(id?) [#createcachestorageid] Use this to retain the previous reference for an equivalent value, keyed by a cache entry and optional group path. Unlike a one-time memoized calculation, callers provide the newly computed value; the cache compares it with the previous one. ```ts import { createCacheStorage } from '@khanglvm/react/helpers' const { cache, clear, uid } = createCacheStorage() const group = uid() const first = cache({ count: 1 }, 'summary', group) const second = cache({ count: 1 }, 'summary', group) console.log(first === second) // true clear(group) ``` `cache(value, entryId, ...groupKeys)` returns the earlier value when `deepEqual` says they match. `clear(...groupKeys)` removes a group path; `uid()` returns a new symbol. All equality limitations above apply. A cached `undefined` counts as empty, so the next call stores its value without comparing. A typical use is a selector for an external store that maps raw data into a new object on every read: passing the result through `cache` returns the same reference while the content is unchanged, which `useSyncExternalStore` requires to avoid rerendering in a loop. The state utility uses it this way for selected values. There is no whole-cache clear: `clear()` with no keys does nothing. Supplying a factory ID fixes the entry ID, but its bound `clear()` does not reliably remove the resulting entry. Prefer the unbound factory with explicit groups, as above, and clear groups when their owner is done. Skip this helper when a stable reference or React `useMemo` already solves the problem. ## Memo comparison [#memo-comparison] `comparePropsForMemo(keys)` builds a comparator for named props. `compareAllPropsForMemo(previous, next)` compares the keys present in the previous props object. Both use `deepEqual`. ```tsx import { memo } from 'react' import { comparePropsForMemo } from '@khanglvm/react/helpers' type LabelProps = { label: string } export const Label = memo( function Label({ label }: LabelProps) { return {label} }, comparePropsForMemo('label'), ) ``` For all existing keys, `memo(Component, compareAllPropsForMemo)` is the companion shorthand; note the added-prop limitation below. These save writing a custom comparator when bounded nested props need value comparison. Default `memo` is usually the simpler starting point. Include every prop that affects output or behavior, including callbacks; an ignored callback can retain stale data. `compareAllPropsForMemo` can miss a newly added prop because it only visits the previous keys. Both follow the collection identity rules of `deepEqual` and do not support cyclic values. React's [memo documentation](https://react.dev/reference/react/memo#specifying-a-custom-comparison-function) explains custom comparator costs and the need to compare function props. These helpers do not promise a faster render. ## Children [#children] The child helpers package repeated checks into named functions. Use them only when their exact rules match your component; most components can simply render `children`. `filterComponentFromChildren` lets a compound component pick its slots out of `children`, such as `...`, and render each slot in its own place. ```tsx import { isEmptyChildren, isPrimitiveChildren, isReactFragmentChildren, filterComponentFromChildren, } from '@khanglvm/react/helpers' isEmptyChildren(null) // true isPrimitiveChildren('Hello') // true isReactFragmentChildren(<>Hello) // true function Tab({ title }: { title: string }) { return {title} } const tabs = filterComponentFromChildren( [, Other], Tab, ) // only the Tab element ``` | Helper | Useful check | Exact behavior and limit | | --- | --- | --- | | `isIterableChildren(children)` | More than one child slot | Checks `Children.count > 1`; a one-item array returns false. The name does not mean general JavaScript iterability. | | `isSingleReactElementChildren(child)` | One non-primitive child slot | Excludes strings, numbers, booleans, null, and undefined. It does not call `isValidElement`; a one-item array can pass. Use React `isValidElement` for element validation. | | `isReactFragmentChildren(child)` | A fragment wrapper | Adds a fragment-type string check to the single-child check. It does not inspect the fragment's contents. | | `isHTMLElementChildren(child)` | A single non-fragment child | Also accepts custom React components; it does not prove a host HTML element. For that, check `isValidElement(child) && typeof child.type === 'string'`. | | `isEmptyChildren(children)` | Absent value | True only for null or undefined; false, an empty string, and an empty array do not pass. | | `isPrimitiveChildren(children)` | Text, number, or boolean | Booleans pass even though React does not render them as visible text. | | `filterComponentFromChildren(children, Component)` | Direct children of a chosen component type | Uses `Children.toArray`, filters valid elements, and checks exact `child.type` identity. It does not search inside fragments or rendered components. | React documents these traversal boundaries in [Children](https://react.dev/reference/react/Children#caveats). These predicates are convenience checks, not validators for all ReactNode shapes. ## Types [#types] These exports affect TypeScript only. Use them to reduce repeated type expressions; they do not validate or change runtime values. | Type | Use and example | Limit | | --- | --- | --- | | `TAssertFunction` | A generic identity signature preserving a subtype: `TAssertFunction<{ id: string }>` | Declares a function type, not an assertion implementation | | `MapKeyType` | Extract a Map key: `MapKeyType>` is string | Non-Map inputs resolve to never | | `MapValueType` | Extract a Map value: `MapValueType>` is number | Non-Map inputs resolve to never | | `ExtractValue` | Retain a constrained member: `ExtractValue<'a' \| 'b', 'a'>` is 'a' | Returns V; it is not the built-in Extract filter | | `TDeepReadonly` | Recursive readonly object/array view: `TDeepReadonly<{ tags: string[] }>` | No runtime freeze; collection handling omits some methods but does not recursively freeze entries or remove every mutator, such as Set.add | | `TDeepMutable` | Remove readonly from nested objects/arrays: `TDeepMutable>` | Built-ins and collection types are largely preserved | | `DistributiveOmit` | Apply Omit to each union member: `DistributiveOmit<{ kind: 'a'; x: number } \| { kind: 'b'; y: string }, 'kind'>` | A compile-time union transformation | | `Prettify` | Expand an object intersection for easier type inspection: `Prettify<{ a: string } & { b: number }>` | Does not transform values | Root exports also include `TContextState` and `TStateManager`, return-type aliases for their factories, plus `LocalizedString` and `TranslationNamespace`, described in the [translation guide](translation.md#13-api-reference). --- # Use with coding agents URL: https://docs.khangle.dev/react/agents ```sh npx skills add khanglvm/react ``` The skill also ships in the npm package at `node_modules/@khanglvm/react/skills/khanglvm-react/SKILL.md`, next to the guides in `node_modules/@khanglvm/react/docs/`, so an agent can read the docs that match the installed version. `llms.txt` in the package indexes them. If you don't install the skill, point the agent at the copy in the package: > Read node_modules/@khanglvm/react/skills/khanglvm-react/SKILL.md and follow it. Then add an English/Vietnamese language switcher to this Next.js app using @khanglvm/react, with the language stored in a cookie. Every guide is also online as plain text: [docs.khangle.dev/react/llms-full.txt](https://docs.khangle.dev/react/llms-full.txt) holds all of them in one file.