Blog>
Snippets

Cross-Framework State Sharing with TanStack Store

Explain how to set up TanStack Store to share state between components written in different frameworks (e.g., React and Vue), focusing on the initialization of a shared store and the use of a custom hook in React and a mixin in Vue for accessing and updating the shared state.
import { createStore } from '@tanstack/store-react';

// Define the initial state
const initialState = { counter: 0 };

// Create a store with the initial state
export const counterStore = createStore({
  initialState
});
This creates a shared store using TanStack Store with an initial state. The counterStore can be used across different components and frameworks.
import { counterStore } from './store';
import { useStore } from '@tanstack/react-store';

export function useCounter() {
  const [state, setState] = useStore(counterStore);
  const increment = () => setState(old => ({ counter: old.counter + 1 }));
  return { counter: state.counter, increment };
}
This is a custom React hook that utilizes the shared store. It provides a way to access and update the counter state, including an increment function.
import { counterStore } from './store';

export const counterMixin = {
  data() {
    return {
      sharedState: counterStore.getState()
    };
  },
  methods: {
    increment() {
      counterStore.setState(old => ({ counter: old.counter + 1 }));
    }
  },
  created() {
    counterStore.subscribe((state) => {
      this.sharedState = state;
    });
  }
};
This Vue mixin is designed to interact with the shared store. It integrates the store's state into the Vue component, allowing the component to read from and write to the shared counter state.