The Bookkeeping Pattern

Published

I've found myself lately working with a decent number of Array.prototype.reduce and useReducer uses. With both of these, I've been reaching for what I'm going to call the "bookkeeping pattern"[1].

Before diving into the code, I wanted to step back a bit and outline when and where this pattern could be useful.

Let's start with a simple example, imagine you have an array of strings, that can contain some duplicates, and we want to narrow it down to only an array of unique strings. Sure, I know you could also import {uniq} from 'lodash' and be done with it (or use [...new Set([...array])]), but let's say that we wanted to implement this logic via Array.prototype.reduce for a minute!

In order to remove the duplicates, we need some way to know if we've "seen" a value before, while we could use some external value for that, we could also stash that value within the result of our reducer. Essentially we manage our own bookkeeping within the reduce call!

Let's look at some code:

1let fruits = [
2 'apple',
3 'banana',
4 'kiwi',
5 'strawberry',
6 'apple'
7];
8
9{
10 // First path, maintaining the bookkeeping separate from the reduce:
11 let seen = new Set();
12 let reducedFruits = fruits.reduce((acc, fruit) => {
13 if (!seen.has(fruit)) {
14 seen.add(fruit);
15 acc.push(fruit)
16 }
17 return acc;
18 }, []);
19}
20
21// Second path - bake in the bookkeeping
22// __within__ the reduce accumulator!
23let reducedFruits = fruits.reduce(
24 (acc, fruit) => {
25 if (!acc.seen.has(fruit)) {
26 acc.seen.add(fruit);
27 acc.fruits.push(fruit);
28 }
29 return acc;
30 },
31 // Note: Our default accumulator changed shape!
32 {
33 fruits: [],
34 seen: new Set()
35 }
36)
37 // Note: We need to grab the value we care about from the reduce call
38 .fruits;
1let fruits = [
2 'apple',
3 'banana',
4 'kiwi',
5 'strawberry',
6 'apple'
7];
8
9{
10 // First path, maintaining the bookkeeping separate from the reduce:
11 let seen = new Set();
12 let reducedFruits = fruits.reduce((acc, fruit) => {
13 if (!seen.has(fruit)) {
14 seen.add(fruit);
15 acc.push(fruit)
16 }
17 return acc;
18 }, []);
19}
20
21// Second path - bake in the bookkeeping
22// __within__ the reduce accumulator!
23let reducedFruits = fruits.reduce(
24 (acc, fruit) => {
25 if (!acc.seen.has(fruit)) {
26 acc.seen.add(fruit);
27 acc.fruits.push(fruit);
28 }
29 return acc;
30 },
31 // Note: Our default accumulator changed shape!
32 {
33 fruits: [],
34 seen: new Set()
35 }
36)
37 // Note: We need to grab the value we care about from the reduce call
38 .fruits;

Alright, you might be saying that this looks like overkill for this example, clearly that [...new Set(fruits)] would be far easier and I would agree for this use case.

Let's talk about a slightly more difficult use case where I've seen this pattern become really useful: managing incremental form submissions within React with useActionState!

Imagine we have a multi-step form, something like a progressive disclosure experience where you enter your name, then your email, and maybe finally a message for example.

We could manage this form state all client side with useState's or a useReducer, and then perform a manual form submission (either mimicking it with fetch, or calling form.requestSubmit()), but we could also build it in a way that should work without JS as well!

Enter useActionState and Server Actions in React, we can build a multi-step form building on the concept of accumulating some state within our reducer (server action)!

In our case, we can stash the formData value on our state so we can read back from it within components to re-fill the fields in the form after a submission.

You can test this out in this minimal demo app, the source for that app is available in this repo.

The gist boils down to both the server action:

1type State = {
2 status: 'name' | 'email' | 'note' | 'error' | 'complete',
3 formData: FormData
4};
5
6async function incrementalSendAction(
7 prevState: State,
8 formData: FormData,
9): Promise<State> {
10 "use server";
11
12 switch (prevState.status) {
13 case "name": {
14 if (formData.get("back") === "true") {
15 return { status: "name", formData };
16 }
17 return { status: "email", formData };
18 }
19 case "email": {
20 if (formData.get("back") === "true") {
21 return { status: "name", formData };
22 }
23 return { status: "note", formData };
24 }
25 case "note": {
26 if (formData.get("back") === "true") {
27 return { status: "email", formData };
28 }
29 // regular submission after filling out all the fields
30 // validate the form data
31 let { name, email, note } = Object.fromEntries(formData.entries());
32 if (!name || !email || !note) {
33 return { status: "error", formData };
34 }
35 // do something with the form data
36 // success!
37 return { status: "complete", formData };
38 }
39 default:
40 return prevState;
41 }
42}
1type State = {
2 status: 'name' | 'email' | 'note' | 'error' | 'complete',
3 formData: FormData
4};
5
6async function incrementalSendAction(
7 prevState: State,
8 formData: FormData,
9): Promise<State> {
10 "use server";
11
12 switch (prevState.status) {
13 case "name": {
14 if (formData.get("back") === "true") {
15 return { status: "name", formData };
16 }
17 return { status: "email", formData };
18 }
19 case "email": {
20 if (formData.get("back") === "true") {
21 return { status: "name", formData };
22 }
23 return { status: "note", formData };
24 }
25 case "note": {
26 if (formData.get("back") === "true") {
27 return { status: "email", formData };
28 }
29 // regular submission after filling out all the fields
30 // validate the form data
31 let { name, email, note } = Object.fromEntries(formData.entries());
32 if (!name || !email || !note) {
33 return { status: "error", formData };
34 }
35 // do something with the form data
36 // success!
37 return { status: "complete", formData };
38 }
39 default:
40 return prevState;
41 }
42}

and the usage of useActionState:

1let [state, action] = useActionState(incrementalSendAction, initialState);
1let [state, action] = useActionState(incrementalSendAction, initialState);

From this - we can access the previous submitted formData via state.formData, allowing us to re-fill the inputs with the previous submitted value:

1<Input
2 name="name"
3 // undefined on first render, filled in after first submission
4 defaultValue={state.formData.get('name')}
5/>
1<Input
2 name="name"
3 // undefined on first render, filled in after first submission
4 defaultValue={state.formData.get('name')}
5/>

Now we get all the benefits:

  • Minimal state management
    • What state there is, lives on the server
  • The form works great with and without JavaScript
  • The rendering logic is easy to reason about

The beauty of this also is that it's "Just React"â„¢ and a minimal pattern built on top of the concepts we learned with Array.prototype.reduce!

Footnotes:

[1] - Although I'm sure that there is an existing name for this concept/pattern - if you know what it is called reach out and I'll update my blog post!