From 5ea1167f61d36a60df7cb9a8eda55f51fb4bb3a8 Mon Sep 17 00:00:00 2001 From: Derek Wene Date: Mon, 30 Nov 2026 23:01:27 +0000 Subject: [PATCH 1/5] Fix: pass the real prevValue from useOnFormValueChange The hook read prevValue with getValues() inside the watch callback, where the form already holds the new value, so onChange always got prevValue === value. Track the previous value in the subscription instead, and add a story test. Also fold in the data-table-filter speedups from #177-#180: Set/Map lookups in removeUniq, intersection and getColumnValues, and a primitive fast path in uniq. Co-Authored-By: Claude Opus 5.5 --- .changeset/tidy-filters-prev-value.md | 5 ++ .../use-on-form-value-change.stories.tsx | 60 +++++++++++++++++++ .../hooks/use-on-form-value-change.ts | 15 +++-- .../src/ui/data-table-filter/core/filters.ts | 5 +- .../src/ui/data-table-filter/lib/array.ts | 16 ++++- 5 files changed, 91 insertions(+), 10 deletions(-) create mode 100644 .changeset/tidy-filters-prev-value.md diff --git a/.changeset/tidy-filters-prev-value.md b/.changeset/tidy-filters-prev-value.md new file mode 100644 index 00000000..c269a11f --- /dev/null +++ b/.changeset/tidy-filters-prev-value.md @@ -0,0 +1,5 @@ +--- +'@lambdacurry/forms': patch +--- + +Fix `useOnFormValueChange` passing the new value as `prevValue`, and speed up data-table filter array helpers (`uniq`, `intersection`, `removeUniq`, `getColumnValues`). diff --git a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx index 492d233f..2e889171 100644 --- a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx +++ b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx @@ -576,3 +576,63 @@ export const ConditionalFields: Story = { ], }; */ + +// ============================================================================ +// Story 4: Previous Value +// ============================================================================ +const previousValueSchema = z.object({ + nickname: z.string(), +}); + +type PreviousValueFormData = z.infer; + +const PreviousValueExample = () => { + const fetcher = useFetcher(); + const [lastChange, setLastChange] = useState<{ prev: string; next: string } | null>(null); + + const rawMethods = useRemixForm({ + resolver: zodResolver(previousValueSchema), + defaultValues: { nickname: 'Al' }, + fetcher, + submitConfig: { action: '/', method: 'post' }, + }); + + const methods = useMemo(() => rawMethods, [rawMethods]); + + const handleNicknameChange = useCallback((next: string, prev: string) => setLastChange({ prev, next }), []); + + useOnFormValueChange({ + name: 'nickname', + methods, + onChange: handleNicknameChange, + }); + + return ( + +
+ +

+ {lastChange ? `Changed from "${lastChange.prev}" to "${lastChange.next}"` : 'No changes yet'} +

+ +
+ ); +}; + +export const PreviousValue: Story = { + play: async ({ canvasElement }: StoryContext) => { + const canvas = within(canvasElement); + + const input = await canvas.findByLabelText(/nickname/i); + expect(canvas.getByTestId('last-change')).toHaveTextContent('No changes yet'); + + await userEvent.type(input, 'ex'); + + await waitFor(() => expect(canvas.getByTestId('last-change')).toHaveTextContent('Changed from "Ale" to "Alex"')); + }, + decorators: [ + withReactRouterStubDecorator({ + routes: [{ path: '/', Component: PreviousValueExample }], + }), + ], +}; diff --git a/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts b/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts index e6334d28..eaa3c84f 100644 --- a/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts +++ b/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts @@ -90,16 +90,21 @@ export const useOnFormValueChange = < const { watch, getValues } = formMethods; + // Track the previous value ourselves: inside a watch callback the form state already holds the + // new value, so getValues(name) cannot provide it. Seeding here also resets it when `name` changes. + let prevValue = getValues(name); + // Subscribe to the field value changes - const subscription = watch(((value, { name: changedFieldName }) => { + const subscription = watch(((_value, { name: changedFieldName }) => { + const currentValue = getValues(name); + // Only trigger onChange if the watched field changed if (changedFieldName === name) { - const currentValue = value[name] as PathValue; - // Get previous value from the form state - const prevValue = getValues(name); - onChange(currentValue, prevValue); } + + // Keep tracking through other updates too (e.g. reset() fires without a field name) + prevValue = currentValue; }) as WatchObserver); // Cleanup subscription on unmount diff --git a/packages/components/src/ui/data-table-filter/core/filters.ts b/packages/components/src/ui/data-table-filter/core/filters.ts index 59b5532a..b4a549e2 100644 --- a/packages/components/src/ui/data-table-filter/core/filters.ts +++ b/packages/components/src/ui/data-table-filter/core/filters.ts @@ -228,9 +228,8 @@ export function getColumnValues( } if (column.options) { - return raw - .map((v) => column.options?.find((o) => o.value === v)?.value) - .filter((v) => v !== undefined && v !== null); + const optionsMap = new Map(column.options.map((o) => [o.value, o.value])); + return raw.map((v) => optionsMap.get(v as string)).filter((v) => v !== undefined && v !== null); } if (column.transformOptionFn) { diff --git a/packages/components/src/ui/data-table-filter/lib/array.ts b/packages/components/src/ui/data-table-filter/lib/array.ts index af9b218d..ac35b732 100644 --- a/packages/components/src/ui/data-table-filter/lib/array.ts +++ b/packages/components/src/ui/data-table-filter/lib/array.ts @@ -1,5 +1,6 @@ export function intersection(a: T[], b: T[]): T[] { - return a.filter((x) => b.includes(x)); + const set = new Set(b); + return a.filter((x) => set.has(x)); } /** @@ -97,9 +98,19 @@ function deepEqual(a: unknown, b: unknown): boolean { export function uniq(arr: T[]): T[] { // Use a Map where key is the deep hash and value is an array of items sharing the same hash. const seen = new Map(); + const primitives = new Set(); const result: T[] = []; for (const item of arr) { + const type = typeof item; + if (item === null || (type !== 'object' && type !== 'function')) { + if (!primitives.has(item)) { + primitives.add(item); + result.push(item); + } + continue; + } + const hash = deepHash(item); if (seen.has(hash)) { // There is a potential duplicate; check the stored items with the same hash. @@ -138,7 +149,8 @@ export function addUniq(arr: T[], values: T[]): T[] { } export function removeUniq(arr: T[], values: T[]): T[] { - return arr.filter((v) => !values.includes(v)); + const set = new Set(values); + return arr.filter((v) => !set.has(v)); } export function isAnyOf(value: T, values: T[]): boolean { From b2360a6d9da1eb6d2a5a6670dedfef849cdfcce5 Mon Sep 17 00:00:00 2001 From: Derek Wene Date: Tue, 1 Dec 2026 14:53:34 +0000 Subject: [PATCH 2/5] Fix: advance tracked prevValue before calling onChange A setValue on the watched field inside onChange re-enters the watch callback synchronously, so the nested call saw a stale prevValue and the outer call then overwrote the newer tracked value. Also use fetcher.Form in the new story. Co-Authored-By: Claude Opus 5.5 --- .../use-on-form-value-change.stories.tsx | 4 ++-- .../remix-hook-form/hooks/use-on-form-value-change.ts | 10 ++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx index 2e889171..9c3459a6 100644 --- a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx +++ b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx @@ -609,12 +609,12 @@ const PreviousValueExample = () => { return ( -
+

{lastChange ? `Changed from "${lastChange.prev}" to "${lastChange.next}"` : 'No changes yet'}

- +
); }; diff --git a/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts b/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts index eaa3c84f..87ba0fd4 100644 --- a/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts +++ b/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts @@ -97,14 +97,16 @@ export const useOnFormValueChange = < // Subscribe to the field value changes const subscription = watch(((_value, { name: changedFieldName }) => { const currentValue = getValues(name); + const previousValue = prevValue; + + // Update tracking on every notification (reset() fires without a field name), and before + // onChange: a setValue on this field inside onChange re-enters this callback synchronously. + prevValue = currentValue; // Only trigger onChange if the watched field changed if (changedFieldName === name) { - onChange(currentValue, prevValue); + onChange(currentValue, previousValue); } - - // Keep tracking through other updates too (e.g. reset() fires without a field name) - prevValue = currentValue; }) as WatchObserver); // Cleanup subscription on unmount From 74bd521c12b78a58ba9eddebdbd882cf47f5d937 Mon Sep 17 00:00:00 2001 From: Derek Wene Date: Tue, 1 Dec 2026 15:09:38 +0000 Subject: [PATCH 3/5] Test: cover same-field normalization in the PreviousValue story onChange now capitalizes the nickname with setValue, which re-enters the hook for the same field. The story logs every (prev, next) pair and fails if the tracked value is updated after onChange instead of before. Co-Authored-By: Claude Opus 5.5 --- .../use-on-form-value-change.stories.tsx | 51 ++++++++++++++++--- 1 file changed, 43 insertions(+), 8 deletions(-) diff --git a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx index 9c3459a6..52a7967b 100644 --- a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx +++ b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx @@ -588,7 +588,7 @@ type PreviousValueFormData = z.infer; const PreviousValueExample = () => { const fetcher = useFetcher(); - const [lastChange, setLastChange] = useState<{ prev: string; next: string } | null>(null); + const [changes, setChanges] = useState([]); const rawMethods = useRemixForm({ resolver: zodResolver(previousValueSchema), @@ -599,7 +599,20 @@ const PreviousValueExample = () => { const methods = useMemo(() => rawMethods, [rawMethods]); - const handleNicknameChange = useCallback((next: string, prev: string) => setLastChange({ prev, next }), []); + // Log every (prev → next) pair, and capitalize the first letter. The setValue call re-enters the + // hook for the same field, so the log also shows that nested changes get the right previous value. + const handleNicknameChange = useCallback( + (next: string, prev: string) => { + // React Hook Form can notify again after setValue without a new value; skip those + if (next === prev) return; + + setChanges((log) => [...log, `${JSON.stringify(prev)} → ${JSON.stringify(next)}`]); + + const capitalized = next.charAt(0).toUpperCase() + next.slice(1); + if (capitalized !== next) methods.setValue('nickname', capitalized); + }, + [methods], + ); useOnFormValueChange({ name: 'nickname', @@ -610,25 +623,47 @@ const PreviousValueExample = () => { return ( - -

- {lastChange ? `Changed from "${lastChange.prev}" to "${lastChange.next}"` : 'No changes yet'} -

+ + {changes.length === 0 ? ( +

No changes yet

+ ) : ( +
    + {changes.map((change, index) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: append-only log, entries can repeat +
  1. {change}
  2. + ))} +
+ )}
); }; +const getChangeLog = (canvas: ReturnType) => + canvas.getAllByRole('listitem').map((item) => item.textContent); + export const PreviousValue: Story = { play: async ({ canvasElement }: StoryContext) => { const canvas = within(canvasElement); const input = await canvas.findByLabelText(/nickname/i); - expect(canvas.getByTestId('last-change')).toHaveTextContent('No changes yet'); + expect(canvas.getByText('No changes yet')).toBeInTheDocument(); + // Plain edits: each change receives the value before it await userEvent.type(input, 'ex'); + await waitFor(() => expect(getChangeLog(canvas)).toEqual(['"Al" → "Ale"', '"Ale" → "Alex"'])); + + // Same-field normalization: typing "a" is rewritten to "A" by setValue inside onChange. + // The nested change must see "a" as its previous value, and the next edit must see "A". + await userEvent.clear(input); + await userEvent.type(input, 'al'); - await waitFor(() => expect(canvas.getByTestId('last-change')).toHaveTextContent('Changed from "Ale" to "Alex"')); + await waitFor(() => expect(input).toHaveValue('Al')); + expect(getChangeLog(canvas).slice(2)).toEqual(['"Alex" → ""', '"" → "a"', '"a" → "A"', '"A" → "Al"']); }, decorators: [ withReactRouterStubDecorator({ From 81d6275a54d4d96108370fd974b485713d28123e Mon Sep 17 00:00:00 2001 From: Derek Wene Date: Tue, 1 Dec 2026 21:00:11 +0000 Subject: [PATCH 4/5] Fix: keep one useOnFormValueChange subscription across renders useRemixForm returns a new methods object every render, so the effect resubscribed and re-read prevValue after each one. A change reported after a re-render (useFieldArray's append) then arrived as (new, new) or was missed. Subscribe on the stable watch/getValues and read onChange through a ref. Also skip notifications that leave the value unchanged: RHF notifies twice for setValue on a controlled field, which reached onChange as (value, value). Co-Authored-By: Claude Opus 5.5 --- .changeset/tidy-filters-prev-value.md | 2 +- .../use-on-form-value-change.stories.tsx | 3 -- .../hooks/use-on-form-value-change.ts | 31 +++++++++++++------ 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/.changeset/tidy-filters-prev-value.md b/.changeset/tidy-filters-prev-value.md index c269a11f..b38a1385 100644 --- a/.changeset/tidy-filters-prev-value.md +++ b/.changeset/tidy-filters-prev-value.md @@ -2,4 +2,4 @@ '@lambdacurry/forms': patch --- -Fix `useOnFormValueChange` passing the new value as `prevValue`, and speed up data-table filter array helpers (`uniq`, `intersection`, `removeUniq`, `getColumnValues`). +Fix `useOnFormValueChange` passing the new value as `prevValue`. The hook now keeps one subscription across renders, so `prevValue` stays correct when a change is reported after a re-render (e.g. `useFieldArray`), and it no longer calls `onChange` when a notification leaves the value unchanged. Also speed up data-table filter array helpers (`uniq`, `intersection`, `removeUniq`, `getColumnValues`). diff --git a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx index 52a7967b..5cff7775 100644 --- a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx +++ b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx @@ -603,9 +603,6 @@ const PreviousValueExample = () => { // hook for the same field, so the log also shows that nested changes get the right previous value. const handleNicknameChange = useCallback( (next: string, prev: string) => { - // React Hook Form can notify again after setValue without a new value; skip those - if (next === prev) return; - setChanges((log) => [...log, `${JSON.stringify(prev)} → ${JSON.stringify(next)}`]); const capitalized = next.charAt(0).toUpperCase() + next.slice(1); diff --git a/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts b/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts index 87ba0fd4..63af2a30 100644 --- a/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts +++ b/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts @@ -1,4 +1,4 @@ -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { useFormContext, type FieldPath, @@ -26,7 +26,8 @@ export interface UseOnFormValueChangeOptions< */ name: TName; /** - * Callback function that runs when the field value changes + * Callback function that runs when the field value changes. + * Not called when a notification leaves the value unchanged (compared with `Object.is`). * @param value - The new value of the watched field * @param prevValue - The previous value of the watched field */ @@ -84,11 +85,21 @@ export const useOnFormValueChange = < const contextMethods = useFormContext(); const formMethods = (providedMethods || contextMethods) as WatchableFormMethods | null; + // `methods` from useRemixForm is a new object on every render, but watch and getValues are stable. + // Subscribing on those (and reading onChange through a ref) keeps one subscription alive across + // renders, so the tracked previous value survives a render that happens before RHF notifies + // (e.g. useFieldArray's append). + const watch = formMethods?.watch; + const getValues = formMethods?.getValues; + const onChangeRef = useRef(onChange); + useEffect(() => { - // Early return if no form methods are available or hook is disabled - if (!enabled || !formMethods || !formMethods.watch || !formMethods.getValues) return; + onChangeRef.current = onChange; + }, [onChange]); - const { watch, getValues } = formMethods; + useEffect(() => { + // Early return if no form methods are available or hook is disabled + if (!enabled || !watch || !getValues) return; // Track the previous value ourselves: inside a watch callback the form state already holds the // new value, so getValues(name) cannot provide it. Seeding here also resets it when `name` changes. @@ -103,14 +114,14 @@ export const useOnFormValueChange = < // onChange: a setValue on this field inside onChange re-enters this callback synchronously. prevValue = currentValue; - // Only trigger onChange if the watched field changed - if (changedFieldName === name) { - onChange(currentValue, previousValue); + // Only trigger onChange if the watched field changed. RHF notifies twice for a setValue on a + // controlled field, so skip notifications that leave the value as it was. + if (changedFieldName === name && !Object.is(currentValue, previousValue)) { + onChangeRef.current(currentValue, previousValue); } }) as WatchObserver); // Cleanup subscription on unmount - return () => subscription.unsubscribe(); - }, [name, onChange, enabled, formMethods]); + }, [name, enabled, watch, getValues]); }; From 1c4c9ac7174957ebe302e1ff49b5272bcfe04289 Mon Sep 17 00:00:00 2001 From: Derek Wene Date: Tue, 1 Dec 2026 21:15:05 +0000 Subject: [PATCH 5/5] Test: cover useFieldArray changes in useOnFormValueChange stories useFieldArray re-renders before it reports a change, so this story fails if the hook's subscription goes back to following the methods object identity. Also type the PreviousValue log helper so the docs typecheck stays clean. Co-Authored-By: Claude Opus 5.5 --- .../use-on-form-value-change.stories.tsx | 67 ++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx index 5cff7775..8b5d37b8 100644 --- a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx +++ b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx @@ -4,6 +4,7 @@ import { useOnFormValueChange } from '@lambdacurry/forms/remix-hook-form/hooks/u import { Select } from '@lambdacurry/forms/remix-hook-form/select'; import { TextField } from '@lambdacurry/forms/remix-hook-form/text-field'; import type { Meta, StoryContext, StoryObj } from '@storybook/react-vite'; +import { useFieldArray } from 'react-hook-form'; import { expect, userEvent, within, waitFor } from '@storybook/test'; import { useState, useMemo, useCallback } from 'react'; import { useFetcher } from 'react-router'; @@ -641,7 +642,7 @@ const PreviousValueExample = () => { }; const getChangeLog = (canvas: ReturnType) => - canvas.getAllByRole('listitem').map((item) => item.textContent); + canvas.getAllByRole('listitem').map((item: HTMLElement) => item.textContent); export const PreviousValue: Story = { play: async ({ canvasElement }: StoryContext) => { @@ -668,3 +669,67 @@ export const PreviousValue: Story = { }), ], }; + +// ============================================================================ +// Story 5: Field Array +// ============================================================================ +type GuestListFormData = { guests: { name: string }[] }; + +const FieldArrayExample = () => { + const fetcher = useFetcher(); + const [changes, setChanges] = useState([]); + + const methods = useRemixForm({ + defaultValues: { guests: [] }, + fetcher, + submitConfig: { action: '/', method: 'post' }, + }); + + const { fields, append } = useFieldArray({ control: methods.control, name: 'guests' }); + + // useFieldArray re-renders before it reports the change, so this also checks that the hook's + // tracked previous value survives a render (useRemixForm returns a new methods object each time). + const handleGuestsChange = useCallback( + (next: GuestListFormData['guests'], prev: GuestListFormData['guests']) => + setChanges((log) => [...log, `${prev.length} → ${next.length} guests`]), + [], + ); + + useOnFormValueChange({ + name: 'guests', + methods, + onChange: handleGuestsChange, + }); + + return ( + + + +

{fields.length} guests

+

{changes.length ? changes.join(', ') : 'No changes yet'}

+
+
+ ); +}; + +export const FieldArray: Story = { + play: async ({ canvasElement }: StoryContext) => { + const canvas = within(canvasElement); + + const addButton = await canvas.findByRole('button', { name: /add guest/i }); + expect(canvas.getByTestId('guest-changes')).toHaveTextContent('No changes yet'); + + await userEvent.click(addButton); + await userEvent.click(addButton); + + await canvas.findByText('2 guests'); + await waitFor(() => expect(canvas.getByTestId('guest-changes')).toHaveTextContent(/^0 → 1 guests, 1 → 2 guests$/)); + }, + decorators: [ + withReactRouterStubDecorator({ + routes: [{ path: '/', Component: FieldArrayExample }], + }), + ], +};