Blog

How the resume context reducer is built

This change is mostly internal. If you use the editor at /build, you will notice one thing: when you add a new position or a new study and then press Cancel, the blank row is gone. It does not show up in the preview, the PDF, or the exported JSON.

The bigger part is what sits underneath. The resume document now lives in one reducer behind a React context, and the preview, the PDF and Export JSON all read from that one store. This post covers how that is put together: the state shape, the actions, why list keys are created outside the reducer, how Cancel and remove work, and two small details around the PDF and the LinkedIn snapshot.

What changed, in one paragraph

Before, the whole editor was one React Hook Form instance in src/components/forms/Form.tsx, shared through FormProvider. Child forms reached into it with useFormContext, read values with watch, wrote with setValue, and the experience and education lists were useFieldArrays. Now the document is a plain useReducer state in ResumeDocumentProvider. The contact, experience and education forms each keep their own local useForm while you type, and pressing Save dispatches one action into the store. No new dependencies were added.

Where the modules live

Piece Path Role
State and actions src/lib/document/state.ts DocumentState, DocumentListKeys, DocumentAction, createInitialDocumentState.
Reducer src/lib/document/reducer.ts resumeDocumentReducer, a pure function.
Action helpers src/lib/document/actions.ts replaceDocument, saveExperience, saveEducation. They create list keys.
Barrel src/lib/document/index.ts Public exports for the module.
Provider and hooks src/components/document/ResumeDocumentProvider.tsx ResumeDocumentProvider, useResumeDocument, useResumeDispatch, useResumeSnapshot.
Mount point src/app/build/page.tsx Wraps the edit screen inside AppProvider.
Consumers src/components/forms/*, src/components/pdf/PdfDownload.tsx Forms dispatch; header, preview, PDF and export read.

The reducer and the action helpers are plain TypeScript with no React imports. The React part is one provider file.

The state shape

// src/lib/document/state.ts
export type DocumentListKeys = {
  experience: string[];
  education: string[];
};

export type DocumentState = {
  values: EditorFormValues;
  keys: DocumentListKeys;
};

values is the same camelCase EditorFormValues the editor already used (personalDetails, contactDetails, experienceItems, educationItems, personalProjects). Nothing about the resume shape changed, so the existing converters, Zod schemas and Export JSON keep working on it.

keys runs in parallel with the two lists: keys.experience[i] belongs to values.experienceItems[i]. The keys are only for React. They are not part of the resume, and export only ever sees values.

The actions are a closed union:

// src/lib/document/state.ts
export type DocumentAction =
  | { type: "replace"; values: EditorFormValues; keys: DocumentListKeys }
  | {
      type: "setContact";
      personalDetails: PersonalDetails;
      contactDetails: ContactDetails;
    }
  | { type: "saveExperience"; index: null; item: ExperienceItem; key: string }
  | { type: "saveExperience"; index: number; item: ExperienceItem }
  | { type: "removeExperience"; index: number }
  | { type: "saveEducation"; index: null; item: EducationItem; key: string }
  | { type: "saveEducation"; index: number; item: EducationItem }
  | { type: "removeEducation"; index: number };

index: null means append, and only the append variant carries a key. Editing an existing row by index has no key field at all, so the type system will not let you hand the reducer a new key for a row that already has one. The reducer ends with an exhaustive never check, so adding an action type without handling it is a compile error.

The provider

// src/components/document/ResumeDocumentProvider.tsx
export function ResumeDocumentProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(
    resumeDocumentReducer,
    undefined,
    createInitialDocumentState,
  );
  const valuesRef = useRef(state.values);
  useLayoutEffect(() => {
    valuesRef.current = state.values;
  }, [state.values]);
  const getSnapshot = useCallback(() => valuesRef.current, []);

  return (
    <DocumentStateContext.Provider value={state}>
      <DocumentDispatchContext.Provider value={dispatch}>
        <DocumentSnapshotContext.Provider value={getSnapshot}>
          {children}
        </DocumentSnapshotContext.Provider>
      </DocumentDispatchContext.Provider>
    </DocumentStateContext.Provider>
  );
}

There are three contexts, not one:

  • State (useResumeDocument) for anything that renders from the document.
  • Dispatch (useResumeDispatch) for anything that changes it. dispatch from useReducer is stable.
  • Snapshot (useResumeSnapshot), a stable function that returns the committed values through a ref.

valuesRef is updated in that layout effect because a ref should not be written during render. React can render an update and then discard it, and a write in the function body would still be there afterwards, so getSnapshot could hand back a document that was never committed. useLayoutEffect runs after the commit and before event handlers, so by the time Export JSON or the LinkedIn flow calls getSnapshot, the ref holds the committed values. The getter stays a stable useCallback with an empty dependency list: it always reads valuesRef.current, and only the effect moves that current forward.

The snapshot getter replaces what getValues() used to do. Export JSON and the LinkedIn flow want the document at click time. LinkedInImport already took a getValues prop, so Form.tsx now passes getSnapshot in that slot and the component did not need a different interface.

Each hook throws if it is used outside the provider, with a message like useResumeDispatch must be used within ResumeDocumentProvider.

Where it mounts

// src/app/build/page.tsx
"use client";

export default function IndexPage() {
  return (
    <AppProvider>
      <ResumeDocumentProvider>
        <Edit />
      </ResumeDocumentProvider>
    </AppProvider>
  );
}

The /build page was already a client component, and the provider file is marked "use client" too. The store exists only while /build is mounted in the browser. There is no server state, no route handler and no server action involved. The editor content stays on the device, as before.

That also explains why the LinkedIn snapshot exists at all: leaving for LinkedIn reloads /build, which throws the in-memory store away, so the editor is copied to sessionStorage first. More on that below.

Why a reducer and context

I want to be careful here and stick to what the code shows.

The editor was already built on a context. FormProvider from React Hook Form shared one form instance with the whole tree, and child components pulled what they needed with useFormContext. So this was never a prop-drilling setup, and I did not want to turn it into one. The new code keeps the same shape: a provider at the top of /build, hooks underneath.

What changed is what sits in that context. Instead of one large form object that every card writes into with setValue, there is a small, typed document with eight action variants and a pure reducer. The reducer lives in src/lib/document with no React dependency, and the project notes now describe it as the pure reducer that owns editor state. Every change to the document goes through one function, which makes the cancel and replace cases easy to read.

An external store library was not needed for this. useReducer and createContext are in React already, and the change adds no dependencies. That is the extent of the argument the code makes. It does not benchmark anything, and I am not going to claim it does.

Forms keep local state, Save dispatches once

Each form still uses React Hook Form, but now as its own local form. The contact form, for example, starts from the store's values and dispatches on submit:

// src/components/forms/ContactDetailsForm.tsx
dispatch({
  type: "setContact",
  personalDetails: {
    name: data.name,
    title: data.title,
    skills: data.skills,
    intro: data.intro,
  },
  contactDetails: {
    email: data.email,
    phone: data.phone,
    linkedin: data.linkedin,
    github: data.github,
    location: data.location,
    website: data.website,
  },
});

That replaces nine separate setValue calls (and a stray console.log). Experience and education item saves look like this:

// src/components/forms/ExperienceItemCard.tsx
const handleSave = (item: ExperienceItem) => {
  dispatch(saveExperience(index, item));
  setIsEditing(false);
};

While you type, nothing outside the form re-renders from the store. The preview and the PDF see the change when you press Save.

The forms also moved from React Hook Form's controlled values option to defaultValues. With local forms that only seed from the store, that is the natural fit, but it means a form will not pick up a change to the store on its own. The code handles that with React keys: item forms get the row's key, and the contact form is keyed on its data:

// src/components/forms/ContactDetailsCard.tsx
<ContactDetailsForm
  key={JSON.stringify({ personalDetails, contactDetails })}
  defaultValues={{ ...personalDetails, ...contactDetails }}
  onSave={() => setIsEditing(false)}
/>

If a LinkedIn apply replaces the document while the contact form is open, the key changes and the form remounts with the new values.

Stable keys, created in action helpers

useFieldArray used to hand out an id per row, and the lists used it as the React key. With plain arrays in a reducer, that job needs a replacement. Keys matter here because each card has local state, for example isEditing. If cards were keyed by index and you removed the second of three rows, the third row would inherit the second row's card state. A key that sticks to the row avoids that.

The keys are created in the action helpers, not in the reducer:

// src/lib/document/actions.ts
function createDocumentKey(): string {
  return crypto.randomUUID();
}

/** New list keys for a full document replace. The reducer stores these as given. */
export function replaceDocument(values: EditorFormValues): DocumentAction {
  return {
    type: "replace",
    values,
    keys: {
      experience: values.experienceItems.map(() => createDocumentKey()),
      education: values.educationItems.map(() => createDocumentKey()),
    },
  };
}

saveExperience and saveEducation follow the same rule. With index === null they mint one key and return an append action. With a number they return an edit action with no key, so an edited row keeps the key it already has.

The reason for keeping key creation out of the reducer is that crypto.randomUUID() gives a different answer every time, and a reducer should give the same output for the same input. React can call a reducer more than once for the same action in Strict Mode during development. If the reducer minted keys, those calls would disagree. With the helpers, the random part happens once, when the action is built, and the reducer only copies what it is given:

// src/lib/document/reducer.ts
case "replace":
  return {
    values: action.values,
    keys: {
      experience: action.keys.experience.slice(),
      education: action.keys.education.slice(),
    },
  };

The list helpers in the reducer keep items and keys in step. Append adds both, remove filters both by the same index, and an edit replaces the item and leaves the keys alone. An out-of-range index is a no-op, and withList returns the previous state object unchanged in that case, so React has nothing to re-render.

The list components render from values and look up the key for each index:

// src/components/forms/ExperienceForm.tsx
{values.experienceItems.map((_, index) => {
  const itemKey = keys.experience[index];
  if (!itemKey) return null;
  return <ExperienceItemCard key={itemKey} index={index} />;
})}

Cancel and remove

Here is the part a user can see. Clicking New Position appends an empty row to the store right away and opens its form:

// src/components/forms/ExperienceForm.tsx
onClick={() =>
  dispatch(saveExperience(null, createEmptyExperienceItem()))
}

The card decides whether to offer Cancel based on whether the row has any content yet:

// src/components/forms/ExperienceItemCard.tsx
<ExperienceItemForm
  key={itemKey}
  onSave={handleSave}
  onCancel={
    experienceItemHasValue(positionData) ? undefined : remove
  }
  defaultValues={positionData}
/>

and remove is one action:

// src/components/forms/ExperienceItemCard.tsx
const remove = () => {
  dispatch({ type: "removeExperience", index });
};

So:

  • New, still empty row: Cancel is shown. It dispatches removeExperience (or removeEducation) for that index, the row and its key leave the store together, and nothing is left behind for the preview, the PDF or Export JSON.
  • Saved row being edited: experienceItemHasValue is true, so onCancel is undefined and the Cancel button is not rendered. You leave edit mode with Save.
  • Remove button on a card: the same remove action, as before.

Education works the same way with saveEducation, removeEducation and educationItemHasValue.

Two honest notes. First, the blank row is in the store while its form is open, because the append happens on click, not on Save. Cancel is what cleans it up. Second, there is no "discard my edits" for a saved row yet. That is a gap, not a design statement.

One store for preview, PDF and export

Form.tsx no longer has a form instance. It reads the document and passes slices down:

// src/components/forms/Form.tsx
const { values } = useResumeDocument();
const dispatch = useResumeDispatch();
const getSnapshot = useResumeSnapshot();
const { personalDetails, contactDetails, experienceItems, educationItems } =
  values;

The header gates (Export JSON and Preview are enabled once there is a name), the preview dialog (Resume) and the PDF (PdfDownload) all take those slices. Export JSON reads getSnapshot() at click time and passes it to the existing buildExportFile. There is no second copy of the resume anywhere on the page.

PDF memoization

PdfDownload now builds its <Document> inside useMemo:

// src/components/pdf/PdfDownload.tsx
const doc = useMemo(
  () => (
    <Document>
      <PageWithStyle>
        {/* personal/contact, experience, education sections */}
      </PageWithStyle>
    </Document>
  ),
  [personalDetails, contactDetails, experienceItems, educationItems],
);

Form re-renders for reasons that have nothing to do with the resume: opening the dialog, showing the export snackbar, switching accordion panels. Without the memo, every one of those renders would hand the PDF link a brand-new <Document> element. With it, the element only changes when one of its four inputs changes.

The memo works well with the reducer because the reducer only creates new references for what it changes. setContact spreads the old values and replaces personalDetails and contactDetails, so experienceItems and educationItems keep their references. A saved experience row leaves the contact slices and educationItems alone.

LinkedIn apply, snapshot restore, and the microtask

Both LinkedIn paths now go through replace:

// src/components/forms/Form.tsx
const applyLinkedInImport = (draft: ImportDraft) => {
  dispatch(replaceDocument(toFormValues(draft, getSnapshot())));
};

and the restore callback passed to LinkedInImport is (restored) => dispatch(replaceDocument(restored)). Every replace gets fresh keys, which is fine: the lists are new, and nothing should keep old card state.

The snapshot needed one fix. Before /build reloads for LinkedIn, the editor is copied into sessionStorage. On the way back, readEditorSnapshot in src/components/forms/LinkedInImport.tsx reads that copy once, removes it from sessionStorage, and keeps it in a module-level cachedSnapshot variable. The cache is there because in development Strict Mode runs the mount effect twice, and the second run must still see the snapshot after the storage key is gone.

The other half of the rule is that a later remount of LinkedInImport must not find the cache still filled and restore an old document over newer edits. So the effect now clears the cache after using it, but not right away:

// src/components/forms/LinkedInImport.tsx
if (snapshot) {
  onRestoreRef.current(snapshot);
  // Drop the cache after it is applied. Deferred so Strict Mode's second
  // effect can still read it; a later remount must not restore again.
  queueMicrotask(() => {
    cachedSnapshot = undefined;
  });
}

queueMicrotask runs after the current synchronous work, so both Strict Mode effect runs see the snapshot, and any later mount finds the cache empty, falls back to sessionStorage, finds nothing there, and leaves the document alone.

What did not change

  • PersonalProjectsForm stays unmounted. Form.tsx does not render it, and personalProjects still is not shown in the preview or the PDF. It is still part of the document and still goes into Export JSON.
  • No new dependencies. React Hook Form and Zod stay, now used per form.
  • The resume shape is the same. The Zod schemas, toFormValues, fromFormValues and buildExportFile did not change.
  • Nothing goes to a server. The store is browser memory on /build.

Why bother

The user-facing win is small, and I would rather say so. A blank row no longer sticks around after Cancel, and preview, PDF and export now read the same store.

The reason to do it now is what comes next. The workspace file already reserves room for variants, and any import or variant switching needs a single place where "the document" lives and a small set of ways to change it. That place now exists, with typed actions and a reducer that can be read in one sitting.

You can try it in the editor at https://resumer.orlinivanov.com/build. Add a position, press Cancel, and open the preview.