React Query and Next.js

2021-07-11

Recently I have been learning Next.js and as a way to practice it, I thought I would convert my CRA Crappit project to Next.js. For all of the data fetching in my app I used react-query, which provides a seemless data fetching, caching, mutation experience. Fortunately, react-query has support for SSR by passing any prefetched data in the initialData options of the useQuery or useInfiniteQuery hooks. This provides a pretty intuitive way to has prerendered data for our markup.


// Prefetch the data on the server
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
    const res = await axios('/api/posts')
    return {
        props: {
            initialPosts: res.data
        }
    };
};

// Initial props is passed to the page components
const HomePage = ({initialPosts}) => {
  const {data , isLoading} = useQuery('posts', () => axios.get('/api/posts'), {initialData: initialPosts})
  
  // Then do whatever you want with your data!
  return (
    
{data.map(post => (
{post.title}
)}
) }

Pretty intutive isn't it? The page will now be sent to the client with prerendered html. Perfect for SEO and speed!