State Management

Understand default state updates, preserve processing records with reducers, and manage message history with MessagesValue.

🎯 Introduction

Ordinary LangGraph state fields replace their previous values by default. A writing assistant, however, needs both the latest article text and a history of reviews and revisions. This article covers default updates, custom merge rules with reducers, and message management with MessagesValue through practical examples.


🧱 Define the Requirements

Suppose a user submits an article and the assistant reviews (review) and then revises (revise) it. The frontend needs the latest text, the issues found by the AI, and the changes it made.

Expected final state:

{
    draft: 'LangGraph can organize tasks. For example: generate an article, then review it.',
    records: ['Missing an example', 'Example added'],
}
FieldExpected update behavior
draftReplace the old text and keep only the latest version
recordsAppend new records and preserve the processing history

First, implement the workflow using the approach from the previous article.


🛠 Implement the Basic Workflow

Create 03.state.mjs in langgraph-demo, using the dependencies already installed.

Define the State

import { StateGraph, StateSchema, START, END } from '@langchain/langgraph';
import { z } from 'zod';

const ArticleState = new StateSchema({
    draft: z.string(),
    records: z.array(z.string()).default(() => []),
});

The user supplies draft, and records starts as an empty array.

Write the Nodes

Append two ordinary functions that simulate review and revision without calling a real model.

Start with the review node:

function reviewArticle() {
    // Simulate an issue found during review
    return {
        records: ['Missing an example'],
    };
}

Add the revision node:

function reviseArticle(state) {
    console.log('Records after review:', state.records);

    // Simulate a revision that adds an example
    return {
        draft: `${state.draft} For example: generate an article, then review it.`,
        records: ['Example added'],
    };
}

Log state.records before revising so you can compare it with the final records.

Connect and Run the Workflow

Append the following:

const builder = new StateGraph(ArticleState);

builder.addNode('review', reviewArticle);
builder.addNode('revise', reviseArticle);

builder.addEdge(START, 'review');
builder.addEdge('review', 'revise');
builder.addEdge('revise', END);

const graph = builder.compile();

const result = await graph.invoke({
    draft: 'LangGraph can organize tasks.',
});

console.log('Final text:', result.draft);
console.log('Final records:', result.records);

Run:

node 03.state.mjs

Expected output:

Records after review: [ 'Missing an example' ]
Final text: LangGraph can organize tasks. For example: generate an article, then review it.
Final records: [ 'Example added' ]

Problem: The final records contain only “Example added.” During sequential execution, LangGraph replaces the fields a node returns by default, including arrays. Fields that are not returned remain unchanged.


🛠 Preserve Processing Records with a Reducer

Why Use a Reducer?

The revision node could append records manually (for comparison only; do not change the code yet):

records: [...state.records, 'Example added'],

This works for sequential execution, but every node updating records must merge the history itself.

A reducer is a merge function for a state field. Once an append rule is attached to records, nodes only return new records, and LangGraph merges them.

Existing state
draft: Initial draft
records: ['Missing an example']
Revision node output
draft: Revised draft
records: ['Example added']
Overwrite by default
Replace the old value with the new one
draft: Revised draft
records
['Example added']
Previous record overwritten
Append with a reducer
current.concat(update)
draft: Revised draft
records
['Missing an example',
 'Example added']
Keep the old record and append the new one
The same node output produces different states under different merge rules. The reducer applies only to records. The draft field still uses replacement.

Write the Merge Function

In 03.state.mjs, add this after the imports and before ArticleState:

function mergeRecords(current, update) {
    return current.concat(update);
}

With the reducer attached, LangGraph calls this function automatically when updating the field:

  • current: Existing records.
  • update: New records from this update.

The return value becomes the merged field value.

Configure the Field's Merge Rule

Add ReducedValue to the existing LangGraph import:

import { StateGraph, StateSchema, ReducedValue, START, END } from '@langchain/langgraph';

Then replace only the records definition in ArticleState with:

records: new ReducedValue(
    z.array(z.string()).default(() => []),
    {
        reducer: mergeRecords,
    },
),

The first argument to ReducedValue defines the field type and default value; the second specifies the merge function. Leave the node and workflow code unchanged.

Verify the Results

Run it again:

node 03.state.mjs

Expected output:

Records after review: [ 'Missing an example' ]
Final text: LangGraph can organize tasks. For example: generate an article, then review it.
Final records: [ 'Missing an example', 'Example added' ]

Here is how the two nodes update records:

NodecurrentupdateMerged result
review[]['Missing an example']['Missing an example']
revise['Missing an example']['Example added']['Missing an example', 'Example added']

Reducers can also merge updates to one field from parallel nodes, avoiding errors when a default field receives multiple updates. We will explore this in the parallel execution article.


🛠 Manage Messages with MessagesValue

Suppose the assistant revises a draft reply. We want the conversation history to retain the user message and final reply, without retaining the draft.

MessagesValue is LangGraph's built-in message state type. It merges messages by ID:

Message IDUpdate behavior
ID is absent from the current message listAppend the new message
ID already exists in the current message listReplace the matching message

Define Message State and Nodes

Create 03.messages.mjs:

import { StateGraph, StateSchema, MessagesValue, START, END } from '@langchain/langgraph';

const ConversationState = new StateSchema({
    messages: MessagesValue,
});

You do not need to define a reducer for messages yourself.

Append two nodes that simulate writing and revising a reply. Start with the writing node:

function writeReply() {
    return {
        messages: [
            {
                id: 'reply-1', // Draft reply
                role: 'assistant',
                content: 'LangGraph can organize tasks.',
            },
        ],
    };
}

Add the revision node:

function reviseReply(state) {
    // The previous node's draft is the last message
    const draft = state.messages.at(-1);

    return {
        messages: [
            {
                id: 'reply-2', // Message ID for the revised reply
                role: 'assistant',
                content: `${draft.content} For example: generate an article, then review it.`,
            },
        ],
    };
}

Observe Messages with Different IDs

Append the graph definition and execution code:

const builder = new StateGraph(ConversationState);

builder.addNode('write', writeReply);
builder.addNode('revise', reviseReply);

builder.addEdge(START, 'write');
builder.addEdge('write', 'revise');
builder.addEdge('revise', END);

const graph = builder.compile();

const result = await graph.invoke({
    messages: [
        { id: 'user-1', role: 'user', content: 'Introduce LangGraph.' },
    ],
});

for (const message of result.messages) {
    console.log(message.id, message.content);
}

Run:

node 03.messages.mjs

Expected output:

user-1 Introduce LangGraph.
reply-1 LangGraph can organize tasks.
reply-2 LangGraph can organize tasks. For example: generate an article, then review it.

The result contains three messages, including the original draft, reply-1.

Update a Message with the Same ID

Change the ID returned by reviseReply() from reply-2 to reply-1:

id: 'reply-1',

Leave everything else unchanged and run node 03.messages.mjs again.

Expected output:

user-1 Introduce LangGraph.
reply-1 LangGraph can organize tasks. For example: generate an article, then review it.

This time there are only two messages, and reply-1 contains the revised reply. A simple array-append reducer does not check IDs and cannot provide this replacement behavior directly.

MessagesValue also converts plain message objects to LangChain message objects that can be passed directly to a model. Restoring message history across requests still requires state persistence, which we will cover later.


❓ Questions and Answers

Q1: With an append reducer, do nodes still need to return the full history?

No. Return only the new records. Returning existing records as well causes the reducer to append them again, creating duplicates.


🧪 Exercise

Add a check node to 03.state.mjs that returns { records: ['Final check complete'] }. Replace the edge from revise to END with edges from revise to check and from check to END.

Run the program again. Confirm that the final text is unchanged and all three processing records are retained in execution order.


🎉 Congratulations! You can now choose state merge rules to match your application requirements.