# messagesStateReducer

> **Function** in `@langchain/langgraph`

📖 [View in docs](https://reference.langchain.com/javascript/langchain-langgraph/index/messagesStateReducer)

Reducer function for combining two sets of messages in LangGraph's state system.

This reducer handles several tasks:
1. Normalizes both `left` and `right` message inputs to arrays.
2. Coerces any message-like objects into real `BaseMessage` instances.
3. Ensures all messages have unique, stable IDs by generating missing ones.
4. If a `RemoveMessage` instance is encountered in `right` with the ID `REMOVE_ALL_MESSAGES`,
   all previous messages are discarded and only the subsequent messages in `right` are returned.
5. Otherwise, merges `left` and `right` messages together following these rules:
   - If a message in `right` shares an ID with a message in `left`:
     - If it is a `RemoveMessage`, that message (by ID) is marked for removal.
     - If it is a normal message, it replaces the message with the same ID from `left`.
   - If a message in `right` **does not exist** in `left`:
     - If it is a `RemoveMessage`, this is considered an error (cannot remove non-existent ID).
     - Otherwise, the message is appended.
   - Messages flagged for removal are omitted from the final output.

## Signature

```javascript
messagesStateReducer(left: Messages, right: Messages): BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]
```

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `left` | `Messages` | Yes | The existing array (or single message) of messages from current state. |
| `right` | `Messages` | Yes | The new array (or single message) of messages to be applied. |

## Returns

`BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]`

A new array of `BaseMessage` objects representing the updated state.

## Examples

```ts
const msg1 = new AIMessage("hello");
const msg2 = new HumanMessage("hi");
const removal = new RemoveMessage({ id: msg1.id });
const newState = messagesStateReducer([msg1], [msg2, removal]);
// newState will only contain msg2 (msg1 is removed)
```

---

[View source on GitHub](https://github.com/langchain-ai/langgraphjs/blob/dc37d3cd62bf88272cdc874e37354ae83ac01660/libs/langgraph-core/src/graph/messages_reducer.ts#L60)