Skip to content

Why do we need batching in signals if React batches state updates? #501

Answered by rschristian
crabvk asked this question in Q&A
Discussion options

You must be logged in to vote

React can batch state updates, but there's no guarantees how or when they will. batch() provides this guarantee.

import { signal, computed, effect } from '@preact/signals-react';

const fName = signal('John');
const lName = signal('Smith');
const fullName = computed(() => `${fName.value} ${lName.value}`);

effect(() => console.log(fullName.value));

fName.value = 'Jane';
lName.value = 'Doe';

This could log:

John Smith
Jane Smith
Jane Doe

Batching the name updates will always log this:

John Smith
Jane Doe

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@rschristian
Comment options

Answer selected by crabvk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants