Ensure we always re-render exactly when the result of loadStory changes

This commit is contained in:
Michael Shilman 2021-09-28 12:50:39 +08:00
parent 28a1d9678e
commit c1883f37bd

View File

@ -21,11 +21,19 @@ export function useStories<TFramework extends AnyFramework = AnyFramework>(
useEffect(() => {
Promise.all(
storyIds.map(async (storyId) => {
// loadStory will be called every single time useStory is called
// because useEffect does not use storyIds as an input. This is because
// HMR can change the story even when the storyId hasn't changed. However, it
// will be a no-op once the story has loaded. Furthermore, the `story` will
// have an exact equality when the story hasn't changed, so it won't trigger
// any unnecessary re-renders
const story = await context.loadStory(storyId);
setStories((current) => ({ ...current, [storyId]: story }));
setStories((current) =>
current[storyId] === story ? current : { ...current, [storyId]: story }
);
})
);
}, storyIds);
});
return storyIds.map((storyId) => storiesById[storyId]);
}