useEffect
Execute a side effect when needed
// we'll create a reusable data loading hook for items
function useItemData({ itemId }) {
// use an atom to store the data
const [getData, setData, data] = useAtom({});
// this hook will be executed after the component has been mounted
// and it will only be executed again if the itemId changes
useEffect(() => {
// ceremony to get a URL and setup an abortable fetch
const url = getItemDataUrl(itemId);
const controller = new AbortController();
const signal = controller.signal;
fetch(url, { signal }).then(response => {
return response.json();
// finally update the data
}).then(setData);
// this function is executed when
// 1. the component is unmounted or
// 2. the itemId changes
// we'll use it to cancel the request if its still running
return () => controller.abort();
}, [itemId]);
return [ getData, data ];
}Execute a side effect on mount and unmount
Use a side effect on mount, every render and unmount
Last updated
Was this helpful?