Sharing Data with Child Components
A common pattern is to fetch data high in your component tree and share it among multiple routes or components, leveraging built-in caching so that each route doesn’t refetch unnecessarily.
Since RemoteDataStore
is both lazy and caching, you can pass the same store to multiple children.
Data is fetched only once, and the results remain in memory as long as a store is in use.
import * as React from 'react';
import {
InvalidationStrategy,
RemoteDataStore,
useRemoteData,
WithRemoteData,
} from 'use-remote-data';
var i = 0;
const freshData = (): Promise<number> =>
new Promise((resolve) => {
i += 1;
setTimeout(() => resolve(i), 1000);
});
export const Component: React.FC = () => {
const store = useRemoteData(freshData, {
invalidation: InvalidationStrategy.refetchAfterMillis(2000),
});
return (
<div>
<Child store={store} />
<Child store={store} />
</div>
);
};
export const Child: React.FC<{ store: RemoteDataStore<number> }> = ({
store,
}) => (
<WithRemoteData store={store}>
{(num, isInvalidated) => (
<p>
<span style={{ color: isInvalidated ? 'darkgray' : 'black' }}>
{num}
</span>
</p>
)}
</WithRemoteData>
);
Should I Pass RemoteDataStore<T>
or Just T
?
There’s a subtle difference:
Does the child component need to render anything while data is still loading?
- If yes, consider passing a
RemoteDataStore<T>
so the child can handle loading/failure states. - Otherwise, if the parent already handles loading and passes down final data, just pass
T
.