Skip to content

Commit

Permalink
updates
Browse files Browse the repository at this point in the history
  • Loading branch information
loganzartman committed Nov 8, 2023
1 parent 35e7116 commit 47ad196
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/app/blog/posts/diy-suspense-in-react.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -186,15 +186,19 @@ Eventually we want the component to _un_-suspend. When React catches the Promise

After a component throws, React doesn't have any magic way to jump back to where the render left off. Instead, it simply re-renders the entire component from scratch. Since suspending can interrupt rendering before all hooks have run, React can't maintain any of the state from the incomplete render. So, when a component is un-suspended, it's like it's remounted.

If the suspending code is implemented correctly, it will not throw the Promise once it's resolved. This allows the rendering to complete, and the component to un-suspend.
If the suspending code is implemented correctly, it will not throw the Promise once the promise has resolved. This allows the rendering to complete, and the component to un-suspend.

## TL;DR

To suspend, we throw a Promise. React catches the Promise at the nearest `<Suspense>` boundary. The children of the `<Suspense>` component are temporarily replaced with its `fallback` tree. When the Promise resolves, React rerenders all the children of the `<Suspense>` boundary. This time, we don't throw the Promise, and the rendering completes.

## Just use `use()`

**Note:** `use()` is currently only available in the canary release of React (18.3).
<Admonition type="note">

`use()` is currently only available in the canary release of React (18.3).

</Admonition>

I think Suspense feels a bit like `await`. It makes a Promise look synchronous by interrupting rendering and restarting once the Promise resolves. I also mentioned how the React team is a bit hesitant about people writing their own code that suspends.

Expand Down
5 changes: 4 additions & 1 deletion src/lib/components/Admonition.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
export type Type = 'note' | 'warning';
export type Type = 'note' | 'warning' | 'tip';

const icons: Record<Type, React.ReactNode> = {
note: <div>🛈</div>,
warning: <div></div>,
tip: <div>💡</div>,
};

const messages: Record<Type, React.ReactNode> = {
note: <div>Note</div>,
warning: <div>Warning!</div>,
tip: <div>Tip</div>,
};

const classNames: Record<Type, string> = {
note: 'text-indigo-100 bg-indigo-500/10 ring-indigo-500',
warning: 'text-amber-100 bg-amber-500/10 ring-amber-500',
tip: 'text-violet-100 bg-violet-500/10 ring-violet-500',
};

export default function Admonition({
Expand Down

0 comments on commit 47ad196

Please sign in to comment.