DEV Community

Cover image for Beginner's Guide to Writing Cleaner React Code with TanStack-Query
Abdullah
Abdullah

Posted on

2

Beginner's Guide to Writing Cleaner React Code with TanStack-Query

Showing data obtained from external sources is a fundamental

Here are the steps to start using React Query to enhance your code:


1.Understand the difference between client state and server state

Client state exists in the browser, such as form state, dark mode, or whether a modal is open or closed. Server state probably resides in a database and is served asynchronously.

Always use React Query for server state. For client state, use native hooks like useState or useReducer.

2. Install React-Query in your project

Follow the installation instructions and remember to set up the query client provider

3. Replace data fetching code and states in your code with the useQuery hook Instead of writing this:

 const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch('https://rickandmortyapi.com/api/character');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const result = await response.json();
        setData(result.results);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, []);
Enter fullscreen mode Exit fullscreen mode

write this:

function fetchRickAndMortyCharacters() {
  return fetch('https://rickandmortyapi.com/api/character')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => data.results);
}

  const { data, isLoading, isError, error } = useQuery(['rickAndMortyCharacters'], fetchRickAndMortyCharacters);
Enter fullscreen mode Exit fullscreen mode

The data you need to render will be in the destructured data. Here is an example of how you can render the result:

 if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>Error: {error.message}</p>;
  if (!data) return <p>No data available</p>;

  return (
    <ul>
      {data.map(character => (
        <li key={character.id}>{character.name}</li>
      ))}
    </ul>
  );
Enter fullscreen mode Exit fullscreen mode

4.Convert the useQuery hook into a custom hook

For better reusability, abstract this into a custom hook:

export function useRickAndMortyCharacters() {
  return useQuery(['rickAndMortyCharacters'], fetchRickAndMortyCharacters);
}
Enter fullscreen mode Exit fullscreen mode

now, from any component, you can just call the custom hook like so:

const { data, isLoading, isError, error } = useRickAndMortyCharacters();
Enter fullscreen mode Exit fullscreen mode

That's it! If you want to go any further, read the docs and play around with different query options or with mutations.

Thanks for reading!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay