Blog>
Snippets

Data Fetching with SWR in Nested Components

Show how to use the SWR hook for data fetching in Next.js 14 within nested components for a seamless data refresh and caching strategy.
import useSWR from 'swr';

// Define your data fetching function
const fetcher = url => fetch(url).then(res => res.json());

// ParentComponent using SWR hook
function ParentComponent() {
    const { data, error } = useSWR('/api/data', fetcher);
    
    if (error) return <div>Failed to load</div>;
    if (!data) return <div>Loading...</div>;
    
    // Pass the fetched data to the child component
    return <ChildComponent data={data} />;
}
This snippet shows a parent component using the useSWR hook to fetch data from an API and pass it to a child component.
// ChildComponent that receives data as props
function ChildComponent({ data }) {
    // Use data in your component
    return (
        <div>
            <h1>Data from Parent Component:</h1>
            <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
    );
}
This snippet shows the child component which receives the fetched data as props from the parent component for rendering.
// NestedChildComponent using SWR with same endpoint
function NestedChildComponent() {
    // Use the same SWR key for automatic data syncing and caching
    const { data, error } = useSWR('/api/data', fetcher);
    
    if (error) return <div>Failed to load nested data</div>;
    if (!data) return <div>Loading nested data...</div>;
    
    return (
        <div>
            <h2>Nested Child Data:</h2>
            <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
    );
}
This snippet shows a nested child component that independently uses the useSWR hook with the same endpoint, benefiting from SWR's caching mechanism.