Blog>
Snippets

Synchronizing State Across Components

Provide an example of how to synchronize state across multiple components using TanStack Store, focusing on a scenario where two components need to share and react to the same state.
import { createStore } from 'tanstack-store-react';

// Define a store with initial state
const useSharedCounterStore = createStore(() => ({
  counter: 0,
  increment: () => {
    useSharedCounterStore.setState((state) => ({ counter: state.counter + 1 }));
  },
  decrement: () => {
    useSharedCounterStore.setState((state) => ({ counter: state.counter - 1 }));
  }
}));
This code snippet creates a TanStack Store with a counter state and two methods to modify the state: increment and decrement. The store is created using the createStore React hook from TanStack Store.
function ComponentA() {
  const { counter, increment } = useSharedCounterStore();
  return (
    <div>
      <p>Counter: {counter}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
This component, ComponentA, uses the shared counter state and the increment function. It displays the counter's current value and provides a button to increment it.
function ComponentB() {
  const { counter, decrement } = useSharedCounterStore();
  return (
    <div>
      <p>Counter: {counter}</p>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}
This component, ComponentB, consumes the same counter state but uses the decrement function. It shows the counter's current value and includes a button to decrement it.