Blog>
Snippets

Identifying and Resolving Reactive Update Issues

Provide a clear example of identifying and resolving issues related to reactive updates in TanStack Config, particularly focusing on the use of useEffect to manage side effects correctly.
import { useEffect } from 'react';
import { useStore } from 'tanstack-store-react';

const MyComponent = () => {
  const [state, actions] = useStore();

  useEffect(() => {
    // Effect to fetch data on component mount
    const fetchData = async () => {
      const data = await fetchSomeData();
      actions.setData(data);
    };
    fetchData();
  }, [actions]);

  // Rendering component logic here
};
This code snippet demonstrates how to use useEffect to correctly manage side effects in a TanStack Store application. It fetches data when the component mounts and updates the store state with this data using actions. By including 'actions' in the dependency array of useEffect, we ensure that the effect runs correctly in response to changes.
const [state, setState] = useStoreState(state => state.someNestedState);

useEffect(() => {
  // Subscribe to external changes, only updating the component state if necessary
  const handleExternalChanges = (newData) => {
    if (newData !== state) {
      setState(newData);
    }
  };
  someExternalSource.subscribe(handleExternalChanges);
  return () => someExternalSource.unsubscribe(handleExternalChanges);
}, [state, setState]);
This example shows how to use useEffect to manage reactive updates from external sources. It subscribes to an external source for changes, updating the component's state only if the new data differs from the current state. This avoids unnecessary re-renders, optimizing performance. The cleanup function ensures the subscription is canceled to prevent memory leaks.