Blog>
Snippets

Using useTransition for Resource Cleanup

Demonstrate how React 18’s useTransition hook can help avoid memory leaks by ensuring that interrupted renders are properly cleaned up.
import { useState, useTransition } from 'react';

function MyComponent() {
    // State for our resource
    const [resource, setResource] = useState();

    // useTransition to manage concurrent mode
    const [startTransition, isPending] = useTransition();

    // Function to load the resource
    const loadResource = (resourceUrl) => {
        startTransition(() => {
            // Fake resource loading API
            fetchResource(resourceUrl).then(newResource => {
                // Set the new resource
                setResource(newResource);
            });
        });
    };

    return (
        <div>
            <button onClick={() => loadResource('/api/resource')}>
                Load Resource
            </button>
            {isPending && <span>Loading...</span>}
            {resource && <div>{resource.content}</div>}
        </div>
    );
}

async function fetchResource(url) {
    const response = await fetch(url);
    const json = await response.json();
    // Convert your fetched data into some resource object
    return { content: json.content };
}
This code snippet includes a sample React component (`MyComponent`) using the `useTransition` hook to manage resource loading. When the 'Load Resource' button is clicked, `loadResource` is called and wrapped in a transition using `startTransition`. This allows React to interrupt the update if needed without leaving the resource loading process in an inconsistent state. Additionally, the component provides visual feedback when a resource is loading by checking the `isPending` state.