• Stars
    star
    168
  • Rank 218,242 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The Master of Suspense ๐Ÿฟ

โ€œThere is no terror in the bang, only in the anticipation of it.โ€

โ€” Alfred Hitchcock

Hitchcock npm version

Hitchcock is a debugging tool for React Suspense. It wraps your calls to React.lazy(), provides a simple cache (based on react-cache) and let you pause, delay or invalidate your promises.

๐Ÿšจ EXPERIMENTAL ๐Ÿšจ

Use this only for experimenting with the new React Concurrent Mode. Hitchcock is inefficient and unstable. Also, I have no idea what I'm doing.

Demos

The code is in the examples folder.

Usage

Try it on CodeSandbox

Add the dependency:

$ yarn add hitchcock

Director

Import the Director component and add it somewhere in your app:

import { Director } from "hitchcock";

function YourApp() {
  return (
    <Director>
      <YourStuff />
    </Director>
  );
}

Lazy

Instead of using React.lazy import lazy from hitchcock:

import { lazy } from "hitchcock";

const HomePage = lazy(() => import("./components/HomePage"));

// Hitchcock's lazy accepts a second parameter with the name of the component:
const ArtistPage = lazy(() => import("./components/ArtistPage"), "ArtistPage");
// it's optional, but recommended, it isn't always easy to guess the name from the import

createResource

import { createResource } from "hitchcock";

const BeerResource = createResource(
  id =>
    fetch(`https://api.punkapi.com/v2/beers/${id}`)
      .then(r => r.json())
      .then(d => d[0]),
  id => `beer-${id}`
);

function Beer({ beerId }) {
  const beer = BeerResource.read(beerId);
  return (
    <>
      <h1>{beer.name}</h1>
      <p>{beer.description}</p>
    </>
  );
}

createResource has two parameters. The first one is a function that returns a promise. The second one is a function that returns an id, that id is used as the key in the cache and also is used as the name of the resource in the debugger.

It returns a resource with a read method that will suspend a component until the resource is ready (when the promise resolves).

Waterfalls

React docs warn about using Suspense as a way to start fetching data when a component renders. The recommended approach is to start fetching before rendering, for example, in an event handler. Hitchcock doesn't solve this problem, but it provides a preload method if you want to try:

import React, { Suspense } from "react";
import ReactDOM from "react-dom";
import { createResource, Director } from "hitchcock";

const BeerResource = createResource(
  id =>
    fetch(`https://api.punkapi.com/v2/beers/${id}`)
      .then(r => r.json())
      .then(d => d[0]),
  id => `beer-${id}`
);

function App() {
  const [beerId, setBeerId] = React.useState(0);
  const deferredBeerId = React.useDeferredValue(beerId, { timeoutMs: 1000 });

  const showBeer = deferredBeerId > 0;

  const handleChange = e => {
    const newBeerId = +e.target.value;
    BeerResource.preload(newBeerId);
    setBeerId(newBeerId);
  };

  return (
    <Director>
      Beer # <input type="number" value={beerId} onChange={handleChange} />
      <Suspense fallback={<div>{`Loading beer #${beerId}...`}</div>}>
        {showBeer && <Beer beerId={deferredBeerId} />}
      </Suspense>
    </Director>
  );
}

function Beer({ beerId }) {
  const beer = BeerResource.read(beerId);
  return (
    <>
      <h1>{beer.name}</h1>
      <p>{beer.description}</p>
    </>
  );
}

const container = document.getElementById("root");
ReactDOM.createRoot(container).render(<App />);

Contributing

$ git clone [email protected]:pomber/hitchcock.git
$ cd hitchcock
$ npx lerna bootstrap

Run the examples:

$ yarn start:example movies
$ yarn start:example suspensify

Publish new version:

$ yarn build:packages
$ npx lerna publish

License

Released under MIT license.

More Repositories

1

git-history

Quickly browse the history of a file from any git repository
JavaScript
13,491
star
2

code-surfer

Rad code slides <๐Ÿ„/>
JavaScript
6,313
star
3

didact

A DIY guide to build your own React
JavaScript
6,105
star
4

stargazer

Your repo reached a stars milestone? Celebrate with a video of your stargazers!
TypeScript
1,242
star
5

covid19

JSON time-series of coronavirus cases (confirmed, deaths and recovered) per country - updated daily
JavaScript
1,230
star
6

placeholdifier

Turn any website into a live wireframe
HTML
351
star
7

scrollycoding-preview

JavaScript
265
star
8

react-lazy-preload-demo

Lazy loading (and preloading) components in Reactย 16.6
JavaScript
122
star
9

intersection-observer-debugger

A script you include during development that shows the root, target, and intersection every time an IntersectionObserver is triggered.
JavaScript
119
star
10

react-fit-to-viewport

TypeScript
118
star
11

site

JavaScript
97
star
12

gpt-docs

An alternative take on OpenAI's Chat Completion official guide and API reference
JavaScript
67
star
13

react-conf-2018-hooks-demo

A copy of Dan's intro to hooks using Code Surfer v3
JavaScript
56
star
14

use-spring

Hooke's law hook
TypeScript
55
star
15

react-svg-curve

React components to draw different types of curves with svg
TypeScript
53
star
16

record-talk-with-remotion

TypeScript
51
star
17

codem-ipsum

Lorem ipsum for code
HTML
42
star
18

the-x-in-mdx

JavaScript
40
star
19

springs

Stiffness? Damping? Mass? Spring Editor
HTML
38
star
20

code-hike-sample

JavaScript
37
star
21

deck-studio

JavaScript
35
star
22

write-code-online

A minimalist code editor
HTML
31
star
23

code-hike-site

JavaScript
31
star
24

create-code-surfer-deck

Initialize a project with mdx deck and code surfer
JavaScript
29
star
25

docusaurus-mdx-2

A Docusaurus theme to add support for MDX v2
TypeScript
27
star
26

gatsby-remark-import-code

Gatsby remark plugin to import code from a file into code blocks
JavaScript
23
star
27

awesome-word-pairs

Opposite word pairs with the same number of letters, ideal for naming your variables.
21
star
28

full-width-text

Web component for making the inner text fit the width of the element
HTML
20
star
29

use-safe-window

React hook to bypass SSR errors when using the window object
JavaScript
19
star
30

escher-bot

https://twitter.com/mauritscorneIis
JavaScript
18
star
31

gatsby-theme-deck-n-blog

Create a deck (with mdx-deck) and a blog post from the same MDX
JavaScript
18
star
32

diagrama

JavaScript
17
star
33

paper-fab-speed-dial

A floating action button flinging out related actions
HTML
16
star
34

mdx-debugger

JavaScript
15
star
35

code-explainers

JavaScript
12
star
36

areyou10x

Quiz: Are you a real 10x programmer?
JavaScript
11
star
37

server-side-media-queries-for-react

JavaScript
9
star
38

codetv

JavaScript
9
star
39

depto_scraper

Scrape apartments from websites searches and upload them in a google spreadsheet
Python
8
star
40

remix-codehike

JavaScript
8
star
41

code-surfer-editor

JavaScript
6
star
42

intersection-observer

Intersection observer code explainer
Svelte
6
star
43

500metros

Hasta dรณnde podรฉs llegar sin pasarte de los 500 metros de distancia
HTML
6
star
44

forkbox

JavaScript
5
star
45

sim-text-edit

JavaScript
5
star
46

incremental-rendering-demo

JavaScript
5
star
47

docs-page-demo

4
star
48

aoe-widget

JavaScript
4
star
49

louis-xiv

React state as a component
JavaScript
4
star
50

css-filters-screencast

HTML
4
star
51

fail-to-pr

Post the relevant part of your broken CI build to the PR that triggered it
JavaScript
4
star
52

blog

Posts by @pomber. JavaScript, React, dev tools, animations and more.
JavaScript
3
star
53

spectacle-another-code-slide

JavaScript
3
star
54

playhead

Component-based animations (coming soon...)
JavaScript
3
star
55

hotkey-trainer

TypeScript
3
star
56

react-vista

JavaScript
3
star
57

dont-panic-js

Answer to the Ultimate Question of JavaScript, the Browser, and Everything
3
star
58

ai-rsc

TypeScript
3
star
59

webcontainer-out-of-memory

JavaScript
2
star
60

nextjs-static-props

JavaScript
2
star
61

next-require-context-issue

JavaScript
2
star
62

react-dx-boilerplate

A react starter kit, based on create-react-app, focused on developer experience
JavaScript
2
star
63

.github

https://help.github.com/en/articles/creating-a-default-community-health-file-for-your-organization
2
star
64

nextjs-mdx-use-client-bug

TypeScript
2
star
65

proto-code-hike-chat

TypeScript
2
star
66

conway

JavaScript
2
star
67

js-action

JavaScript
1
star
68

magic-browser-support-ball

JavaScript
1
star
69

polymer-1-samples

Polymer 1 samples
HTML
1
star
70

yarn-workspaces-code-sharing

JavaScript
1
star
71

empty

1
star
72

hylia

HTML
1
star
73

client-server-bundler

Bundle client and server folders into one build folder including a proxy server to handle static files
JavaScript
1
star
74

bondify

JavaScript
1
star
75

crochet

React without renderers, if you want an effect you use a hook (WIP - Paused)
JavaScript
1
star
76

ch-v1-inngest

TypeScript
1
star