Use Tanstack React Query for Local State Management

Use react query for state management. Sharing data across components.

Example Use cases

import { useQuery } from 'react-query';

const MyComponent = () => {
  const { data } = useQuery('myData', fetchData);

  // Retrieve the data from localStorage
  useEffect(() => {
    const storedData = localStorage.getItem('myData');

    if (storedData) {
      queryClient.setQueryData('myData', JSON.parse(storedData));  //set the data
    }
  }, []);

  // Rest of your component code
};

Setting State Data

const queryClient = useQueryClient()

 queryClient.setQueryData('myDataState', JSON.parse(storedData));  //set the data

Data Can be accessed in a component

const queryClient = useQueryClient()
    
const data = queryClient.getQueryData(['myDataState']);

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *