SolWipe logoSolWipeCheck Wallet
You might have SOL you don't know about. Check for free.
Building Solana Frontends Web3js

Using React Query for Data Fetching with Solana

SW
SolWipe Team
··3 min read

React Query is a powerful tool for managing server state in your React applications, making it particularly useful for building Solana dApps. If you’re looking to streamline data fetching, caching, and synchronization in your Solana projects, using React Query as your Solana datasource can greatly enhance your development experience. This tutorial will walk you through setting up React Query in your app, fetching Solana data, and best practices for caching.

Introduction to React Query

React Query is a data-fetching library that simplifies the process of working with asynchronous data in React applications. It provides a set of hooks that enable you to fetch, cache, and update data easily, without the need for complex state management.

Some of the key benefits of using React Query include:

  • Automatic Caching: React Query caches your data, reducing the number of requests to your server.
  • Background Data Synchronization: It automatically refetches data in the background, ensuring your app always displays the most current information.
  • Query Invalidation: You can easily invalidate and refetch data when it changes, keeping your application state consistent.

These features make React Query an ideal choice for dApps that need to interact with the Solana blockchain.

Setting Up React Query in Your App

To get started with React Query in your Solana dApp, you need to install the library and set up a provider in your application.

Step 1: Install React Query

You can install React Query using npm or yarn. Open your terminal and run:

npm install @tanstack/react-query

or

yarn add @tanstack/react-query

Step 2: Set Up the Query Client

Once you've installed React Query, you need to create a Query Client and wrap your application with the QueryClientProvider. This allows you to use React Query throughout your app.

Here’s a simple example of how to set this up:

import React from 'react';
import ReactDOM from 'react-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';

const queryClient = new QueryClient();

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);

Your application is now ready to use React Query for data fetching!

Fetching Solana Data

Fetching data from the Solana blockchain can be done using the Solana web3.js library in conjunction with React Query. This enables you to create a seamless experience when interacting with Solana data.

Step 1: Set Up Solana Web3.js

First, you need to install the Solana web3.js library:

npm install @solana/web3.js

Step 2: Fetching Data from Solana

Now, let’s create a custom hook to fetch data from the Solana blockchain. For example, we’ll fetch the balance of a wallet address. Here’s how you can do it:

import { useQuery } from '@tanstack/react-query';
import { Connection, clusterApiUrl } from '@solana/web3.js';

const fetchBalance = async (publicKey) => {
  const connection = new Connection(clusterApiUrl('mainnet-beta'), 'confirmed');
  const balance = await connection.getBalance(publicKey);
  return balance;
};

export const useWalletBalance = (publicKey) => {
  return useQuery(['walletBalance', publicKey], () => fetchBalance(publicKey), {
    enabled: !!publicKey, // Only run the query if the publicKey is available
  });
};

Step 3: Using the Custom Hook in Your Component

You can now use this custom hook in your component:

import React from 'react';
import { useWalletBalance } from './hooks/useWalletBalance';

const WalletBalance = ({ publicKey }) => {
  const { data, isLoading, error } = useWalletBalance(publicKey);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error fetching balance: {error.message}</div>;

  return <div>Wallet Balance: {data / 1e9} SOL</div>; // Convert lamports to SOL
};

export default WalletBalance;

This component will fetch and display the wallet balance using React Query, making it easy to manage the state of your Solana dApp data.

Best Practices for Caching

Caching is one of the core features of React Query, and employing best practices can significantly enhance the performance of your Solana application. Here are some tips to get the most out of caching:

1. Set Appropriate Stale Time

You can configure how long data should be considered "fresh" before React Query automatically refetches it. This is controlled by the staleTime option:

useQuery(['walletBalance', publicKey], fetchBalance, {
  staleTime: 10000, // 10 seconds
});

2. Use Query Invalidation

If you're updating data (for instance, after a transaction), you can invalidate the relevant queries to ensure that the app fetches the most current data. This can be done using the queryClient:

const queryClient = useQueryClient();
queryClient.invalidateQueries(['walletBalance', publicKey]);

3. Leverage Query Keys

Using specific query keys helps in managing multiple queries effectively. For example, if your app deals with multiple wallets, ensure each query has a unique key based on the wallet address:

useQuery(['walletBalance', walletAddress], fetchBalance);

4. Prefetch Data

If you anticipate that a user will need certain data, you can prefetch it using the prefetchQuery method. This can improve the perceived performance of your application:

queryClient.prefetchQuery(['walletBalance', publicKey], fetchBalance);

By implementing these best practices, you can optimize your Solana dApp's performance, ensuring that users have a smooth and responsive experience.

Conclusion

Using React Query as your Solana datasource streamlines the process of data fetching and caching in your Solana dApps. By following the steps outlined in this tutorial, you can set up React Query, fetch Solana data, and implement best practices for caching effectively.

If you're interested in more resources related to building on the Solana blockchain, consider checking out the SolWipe guide for additional tools that can help you manage your token accounts, or learn about what are token accounts for a deeper understanding of Solana's architecture.

Start building your Solana dApp today with React Query and unlock the full potential of your data fetching capabilities!

Recover your hidden SOL now

Connect your wallet, scan for free, and claim your locked SOL in under 30 seconds.

Find My Hidden SOL →

More from SolWipe

View all articles →
Advanced Wallet Features Multisig

10 Best Tools for Managing Squads on Solana

Squad management in the Solana ecosystem is essential for teams looking to streamline their operations and enhance collaboration. With the rise of decentralized finance and blockchain applications, managing squads effectively has become crucial. Utilizing the

Feb 20, 2026
Decentralized Storage Computing Filecoin

10 Best Use Cases for the Akash Network in 2026

The Akash Network is revolutionizing the way we think about cloud computing by providing a decentralized platform for hosting applications and services. By connecting users in need of cloud resources with providers who have excess computing power, Akash Networ

Feb 20, 2026
Privacy Cryptocurrency Mixers Zeroknowledge

10 Crypto Mixers You Should Know About in 2026

When it comes to maintaining crypto anonymity, using top crypto mixers is a crucial step for individuals looking to enhance their privacy in transactions. As the landscape of cryptocurrency continues to evolve, ensuring your digital footprint remains discreet

Feb 20, 2026
Solana Blockchain Explorers Analytics

10 Must-Know Solana Data Tools for Investors in 2023

Investing in the Solana blockchain can be both exciting and daunting. With its rapid growth and innovative technology, the need for effective Solana data tools for investors is more crucial than ever. These tools help you make informed decisions, analyze marke

Feb 20, 2026
Blockchain Technology Fundamentals Blockchains

10 Ways Consensus Algorithms Impact Blockchain Performance

Consensus algorithms are a foundational element of blockchain technology, determining how transactions are validated and how nodes in the network come to an agreement. Understanding how consensus algorithms impact blockchain performance is crucial for anyone i

Feb 20, 2026
Sol Investing Fundamentals Buying

2023 Solana Investment Trends: What You Need to Know

The Solana blockchain has gained significant traction in the crypto space, and understanding the Solana investment trends for 2023 can help you make informed decisions. As the ecosystem evolves, it’s essential to stay updated on market dynamics, emerging use c

Feb 20, 2026