Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>React.withHooks() factory API: Live examples</h1>
<main>Loading scripts…</main>
              
            
!

CSS

              
                *,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  font-size: 13px;
  background-color: #1d1e22;
  font-family: 'BlinkMacSystemFont', 'Lucida Grande', 'Segoe UI', Ubuntu, Cantarell, sans-serif;
}

body,
a:hover,
a:active,
a:focus,
input:not([type="checkbox"]),
textarea,
button {
  color: rgb(173, 175, 188);
}

input:not([type="checkbox"])::placeholder {
  color: rgba(173, 175, 188, 0.5);
}

a,
a:link,
a:visited {
  color: rgba(173, 175, 188, 0.8);
}

input:not([type="checkbox"]),
textarea {
  border: none;
  padding: 3px 5px;
  font-size: 14px;
  line-height: 1.2;
}

input:not([type="checkbox"]),
textarea,
button {
  background-color: rgb(68, 72, 87);
  border-radius: 3px;
  border: 2px solid rgb(68, 72, 87);
}
input:not([type="checkbox"]):focus,
textarea:focus,
button:focus {
  outline: none;
  border-color: steelblue;
}

input:not([type="checkbox"]):not(:last-child),
textarea:not(:last-child),
button:not(:last-child) {
  margin-right: 5px;
}

textarea {
  resize: none;
}

button {
  -webkit-appearance: none;
  font-size: 14px;
  font-weight: normal;
  line-height: 1.2;
  display: inline-block;
  padding: 3px 10px;
  cursor: pointer;
  white-space: nowrap;
  text-overflow: ellipsis;
  text-decoration: none;
  text-align: center;
}

button:hover {
  background-color: rgb(90, 95, 115);
}

button.lg {
  font-size: 16px;
  line-height: 1.5;
  padding: 5px 20px;
}

h1 {
  text-align: center;
}

::-webkit-scrollbar {
  width: 12px;
  height: 12px;
}
::-webkit-scrollbar-corner,
::-webkit-scrollbar-track,
::-webkit-scrollbar-track-piece,
::-webkit-scrollbar-button {
  background: transparent;
}
::-webkit-scrollbar-thumb {
  background-color: rgba(173, 175, 188, 0.8);
  background-clip: padding-box;
  border: 3px solid transparent;
  border-radius: 6px;
}

.App-example {
  margin-bottom: 30px;
}

.App-example:last-child {
  margin-bottom: 20px;
}

.App-example-title {
  margin-top: 0;
  margin-bottom: 5px;
}

.App-actions {
  margin: 10px 0;
}

.CodePreview {
  display: flex;
  position: relative;
}

.CodePreview > * {
  flex: 1;
  position: relative;
  height: 100%;
  overflow: auto;
}

.CodePreview > *:not(:first-child) {
  margin-left: 5px;
}

.CodePreview > *:not(:last-child) {
  margin-right: 5px;
}

.CodeEditor {
  width: 100%;
  border-radius: 3px;
  overflow: hidden;
}

.CodeEditor .CodeMirror-scrollbar-filler,
.CodeEditor .CodeMirror-gutter-filler {
  background-color: transparent;
}

.ErrorHandler {
  white-space: pre;
  font-family: monospace;
  font-size: 14px;
}

              
            
!

JS

              
                patchReactHooks(React);

const EXAMPLES = [
  {
    title: <code>useState</code>,
    value:
`React.withHooks(() => {
  const inputState = React.useState('');
  return (props) => {
    const [value, setValue] = inputState;
    return (
      <>
        <input
          placeholder="Type here…"
          value={value}
          onChange={(e) => setValue(e.currentTarget.value)}
        />
        <button onClick={() => setValue('')}>Reset</button>
        <p>Current value: {value || 'N/A'}</p>
      </>
    );
  };
})`
  },
  {
    title: <><code>useState</code> (lazy initial value)</>,
    value:
`React.withHooks(() => {
  const inputState = React.useState((props) => 'Hello, world!');
  return (props) => {
    const [value, setValue] = inputState;
    return (
      <>
        <input
          placeholder="Type here…"
          value={value}
          onChange={(e) => setValue(e.currentTarget.value)}
        />
        <button onClick={() => setValue('')}>Reset</button>
        <p>Current value: {value || 'N/A'}</p>
      </>
    );
  };
})`
  },
  {
    title: <code>useEffect</code>,
    value:
`React.withHooks(() => {
  React.useEffect((props) => {
    const handleResize = console.log.bind(null, 'RESIZE');
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  });
  return (props) => '[Check console for window resize events]';
})`
  },
  {
    title: <code>useRef</code>,
    value:
`React.withHooks(() => {
  const inputEl = React.useRef((props) => null);
  const onButtonClick = () => {
    inputEl.current.focus();
  };
  return (props) => {
    return (
      <>
        <input ref={inputEl} type="text" />
        <button onClick={onButtonClick}>Focus the input</button>
      </>
    );
  };
})`
  },
  {
    title: <code>useCallback</code>,
    value:
`React.withHooks(() => {
  const inputState = React.useState('Hello, world!');
  const onButtonClick = React.useCallback(
    (props) => (
      () => {
        const [input] = inputState;
        alert(input);
      }
    ),
    (props) => [inputState[0]]
  );
  return (props) => {
    const [input, setInput] = inputState;
    return (
      <>
        <input value={input} onChange={(e) => setInput(e.currentTarget.value)} />
        <button onClick={onButtonClick}>Alert</button>
      </>
    );
  };
})`
  },
  {
    title: <code>useMemo</code>,
    value:
`React.withHooks(() => {
  const inputState = React.useState('3 + 5');
  const getMemoizedResult = React.useMemo(
    (props) => {
      const [input] = inputState;
      if (!input) { return ''; }
      try {
        const parsedCode = Babel.transform(input, {}).code;
        return eval(input);
      } catch (e) {
        return e;
      }
    },
    (props) => [inputState[0]],
  );
  return (props) => {
    const [input, setInput] = inputState;
    const result = getMemoizedResult();
    return (
      <>
        <input value={input} onChange={(e) => setInput(e.currentTarget.value)} />
        <p>Result:</p>
        <pre>{result && result.toString()}</pre>
      </>
    );
  };
})`
  },
  {
    title: 'Interdependent hooks',
    value:
`React.withHooks(() => {
  const usersState = React.useState([]);
  const loadingState = React.useState(false);
  const filterState = React.useState('');
  React.useEffect(
    () => {
      const [users, setUsers] = usersState;
      const [filter] = filterState;
      const [loading, setLoading] = loadingState;
      let isCurrentRequest = true;
      setLoading(true);
      fetch('https://jsonplaceholder.typicode.com/users')
        .then((response) => {
          const SIMULATED_DELAY = 300;
          return new Promise((resolve) => setTimeout(resolve.bind(null, response), 300));
        })
        .then((response) => {
          if (!response.ok) { throw new Error('Network error'); }
          return response.json();
        })
        .then((users) => {
          if (!filter) { return users; }
          const filterWords = filter.split(/\\W+/).filter(Boolean).map((word) => word.toLowerCase());
          const filteredUsers = users.filter((user) => filterWords.every(
            (word) => user.name.toLowerCase().includes(word)
          ));
          return filteredUsers;
        })
        .then((filteredUsers) => {
          if (!isCurrentRequest) { return; }
          setUsers(filteredUsers);
          setLoading(false);
        })
        .catch((e) => {
          setLoading(false);
          throw e;
        });
      return () => {
        isCurrentRequest = false;
      };
    },
    (props) => [filterState[0]]
  )
  return (props) => {
    const [users] = usersState;
    const [loading] = loadingState;
    const [filter, setFilter] = filterState;
    return (
      <>
        <input
          type="search"
          placeholder="Filter by name"
          value={filter}
          onChange={(e) => setFilter(e.currentTarget.value)}
        />
        {loading ? (
          <p>Loading…</p>
        ) : (users.length === 0) ? (
          <p>No matching users</p>
        ) : (
          <ul>
            {users.map((user) => <li key={user.id}>{user.name}</li>)}
          </ul>
        )}
      </>
    );
  };
})`
  },
  {
    title: 'Custom hooks',
    value:
`(() => {

  function useOptimisticUpdate(initialValue, { set }) {
    return React.createHook(() => {
      const valueState = React.useState(initialValue);
      const updatingState = React.useState(false);
      const updateValue = React.useCallback(
        (props) => (
          (value) => {
            const [, setUpdating] = updatingState;
            const [previousValue, setValue] = valueState;
            setUpdating(true);
            setValue(value);
            set(value).then(() => {
              setUpdating(false);
            }).catch(() => {
              setUpdating(false);
              setValue(previousValue);
            });
          }
        ),
        []
      );
      return (props) => {
        const [currentValue] = valueState;
        const [updating] = updatingState;
        return [currentValue, updateValue, updating];
      };
    });
  }

  return React.withHooks(() => {
    const valueState = useOptimisticUpdate('foo', {
      set: (value) => new Promise((resolve) => setTimeout(resolve, 1000)),
    });
    return (props) => {
      const [value, setValue, isValueUpdating] = valueState;
      return <>
        <select value={value} onChange={(e) => setValue(e.currentTarget.value)}>
          <option value="foo">foo</option>
          <option value="bar">bar</option>
          <option value="baz">baz</option>
        </select>
        <p>Current value: {value} {isValueUpdating ? '⏳' : '✅'}</p>
      </>
    };
  });

})()`
  },
  {
    title: 'Custom hook composition',
    value:
`(() => {

  function useFooBar({ foo: initialFoo, bar: initialBar }) {
    return React.createHook(() => {
      const fooState = useFoo(initialFoo);
      const barState = useBar(initialBar);
      const update = React.useCallback(
        (props) => (
          (value) => {
            const { set: setFoo } = fooState;
            const { set: setBar } = barState;
            setFoo(value.foo);
            setBar(value.bar);
          }
        ),
        (props) => [],
      );
      return (props) => {
        const { current: foo, set: setFoo } = fooState;
        const { current: bar, set: setBar } = barState;
        return { foo, bar, update };
      };
    });
  }

  function useFoo(initialValue) {
    return React.createHook(() => {
      const valueState = React.useState(initialValue);
      return (props) => {
        const [value, setValue] = valueState;
        return { current: value, set: setValue };
      };
    });
  }

  function useBar(initialValue) {
    return React.createHook(() => {
      const valueState = React.useState(initialValue);
      return (props) => {
        const [value, setValue] = valueState;
        return { current: value, set: setValue };
      };
    });
  }

  return React.withHooks(() => {
    const fooBarState = useFooBar({ foo: 'foo', bar: 'bar' });
    return (props) => {
      const { foo, bar, update } = fooBarState;
      return <>
        <input value={foo} onChange={(e) => update({ foo: e.currentTarget.value, bar })} />
        <input value={bar} onChange={(e) => update({ foo, bar: e.currentTarget.value })} />
        <p>Current value: {foo} {bar}</p>
      </>
    };
  });

})()`
  },
  {
    title: 'Throw error when definining hooks within render function',
    value:
`React.withHooks(() => {
  return (props) => {
    const [value, setValue] = React.useState('');
    return (
      <>
        <input
          placeholder="Type here…"
          value={value}
          onChange={(e) => setValue(e.currentTarget.value)}
        />
        <button onClick={() => setValue('')}>Reset</button>
        <p>Current value: {value || 'N/A'}</p>
      </>
    );
  };
})`
  },
  {
    title: 'Throw error when accessing hook values outside render function',
    value:
`React.withHooks(() => {
  const [value, setValue] = React.useState('');
  return (props) => {
    return (
      <>
        <input
          placeholder="Type here…"
          value={value}
          onChange={(e) => setValue(e.currentTarget.value)}
        />
        <button onClick={() => setValue('')}>Reset</button>
        <p>Current value: {value || 'N/A'}</p>
      </>
    );
  };
})`
  },
  {
    title: 'Throw error when accessing hook values within async callback',
    value:
`React.withHooks(() => {
  const counterState = React.useState(0);
  return (props) => {
    const [counter, setCounter] = counterState;
    return (
      <>
        <p>Current value: {counter}</p>
        <button
          onClick={() => {
            const [counter] = counterState;
            setValue(counter + 1);
          }}
        >
          Increment
        </button>
        <p>[Check console for errors]</p>
      </>
    );
  };
})`
  },
  {
    title: 'Throw error when accessing hook values within cleanup function',
    value:
`React.withHooks(() => {
  const eventState = React.useState('unload');
  React.useEffect(
    (props) => {
      const [event] = eventState;
      if (!event) { return; }
      const handleEvent = console.log.bind(null, 'EVENT:');
      window.addEventListener(event, handleEvent);
      return () => {
        const [event] = eventState;
        window.removeEventListener(event, handleEvent);
      };
    },
    (props) => [eventState[0]]
  );
  return (props) => {
    const [event, setEvent] = eventState;
    return (
      <>
        Subscribed event type: <select
          value={event}
          onChange={(e) => setEvent(e.currentTarget.value)}
        >
          <option value="load">load</option>
          <option value="unload">unload</option>
          <option value="resize">resize</option>
          <option value="scroll">scroll</option>
        </select>
      </>
    );
  };
})`
  },
  {
    title: 'Backwards compatibility with existing hooks API',
    value:
`(props) => {
  const [value, setValue] = React.useState('');
  return (
    <>
      <input
        placeholder="Type here…"
        value={value}
        onChange={(e) => setValue(e.currentTarget.value)}
      />
      <button onClick={() => setValue('')}>Reset</button>
      <p>Current value: {value || 'N/A'}</p>
    </>
  );
}`
  },
];

const TEMPLATE = {
  title: 'Untitled example',
  value:
`React.withHooks(() => {
  // Create hooks here
  return (props) => {
    // Access hook values here
    return (
      <div>
        Hello, world!
      </div>
    );
  };
})`
};

require([
  {
    src: '//unpkg.com/react-codemirror2@5.1.0/index.js',
    dependencies: { 'react': React, 'codemirror': CodeMirror },
  },
]).then(([ReactCodeMirror]) => {
  const { Controlled: CodeMirror } = ReactCodeMirror;

  const CODEMIRROR_OPTIONS = {
    mode: 'jsx',
    lineNumbers: true,
  };

  const App = React.withHooks(function App() {
    const examplesState = React.useState((props) => props.examples.slice());
    return (props) => {
      const [examples, setExamples] = examplesState;
      const { template } = props;
      return (
        <div className="App">
          <div className="App-examples">
            {examples.map(({ title, value }, index) => (
              <div key={index} className="App-example">
                <h2 className="App-example-title">{title}</h2>
                <CodePreview value={value} />
              </div>
            ))}
          </div>
          <div className="App-actions">
            <button
              className="lg"
              onClick={() => setExamples((previousExamples) => [
                ...previousExamples,
                { title: template.title, value: template.value }
              ])}
            >
              Add an example…
            </button>
          </div>
        </div>
      );
    };
  });

  const CodePreview = React.withHooks(function CodePreview() {
    const valueState = React.useState((props) => props.value);
    return (props) => {
      const { rows = 12 } = props;
      const [value, setValue] = valueState;
      return (
        <div className="CodePreview">
          <div>
            <CodeEditor rows={rows} value={value} onChange={setValue} />
          </div>
          <div>
            <ErrorHandler>
              <ComponentRenderer source={value} />
            </ErrorHandler>
          </div>
        </div>
      );
    };
  });

  const CodeEditor = React.withHooks(function CodeEditor() {
    const handleChange = React.useCallback(
      (props) => (editor, data, value) => props.onChange(value),
      (props) => [props.onChange]
    );
    return (props) => {
      const { value } = props;
      return (
        <CodeMirror
          className="CodeEditor"
          value={value}
          options={CODEMIRROR_OPTIONS}
          onBeforeChange={handleChange}
        />
      );
    }
  });

  const ComponentRenderer = React.withHooks(function ComponentRenderer() {
    const getComponent = React.useMemo(
      (props) => parseReactComponent(props.source),
      (props) => [props.source]
    );
    return (props) => {
      const Component = getComponent();
      return <Component />;
    };
  });

  function parseReactComponent(source) {
    return eval(Babel.transform(source, { presets: ['react'] }).code);
  }


  class ErrorHandler extends React.Component {
    constructor(props, context) {
      super(props, context);
      this.state = { error: undefined };
    }
    render() {
      const { children } = this.props;
      const { error } = this.state;
      if (error) {
        return <div className="ErrorHandler">⚠️ {error.toString()}</div>;
      }
      return children;
    }
    componentDidCatch(error) {
      this.setState({ error })
    }
    componentWillReceiveProps() {
      this.setState({ error: undefined });
    }
  }

  ReactDOM.render(
    <App examples={EXAMPLES} template={TEMPLATE} />,
    document.getElementsByTagName('main')[0]
  );
});

function patchReactHooks(React) {
  const PHASE_FACTORY = 'factory';
  const PHASE_RENDER = 'render';
  const PHASE_CLEANUP = 'cleanup';
  const PHASE_CALLBACK = 'callback';

  const Lifecycle = (() => {
    let currentPhase = undefined;
    let hooks = undefined;
    let deferredHooks = undefined;
    return {
      isRenderPhase() { return (currentPhase === PHASE_RENDER); },
      isFactoryPhase() { return (currentPhase === PHASE_FACTORY) },
      isCallbackPhase() { return (currentPhase === PHASE_CALLBACK) },
      isCleanupPhase() { return (currentPhase === PHASE_CLEANUP) },
      withPhase(phase, fn) {
        return (...args) => {
          const previousPhase = currentPhase;
          currentPhase = phase;
          try {
            return fn(...args);
          } catch (e) {
            throw e;
          } finally {
            currentPhase = previousPhase;
          }
        };
      },
      createCallback(fn) {
        return this.withPhase(PHASE_CALLBACK, fn);
      },
      createCleanup(fn) {
        return this.withPhase(PHASE_CLEANUP, fn);
      },
      registerHook(factory, { defer }) {
        if (!hooks) {
          throw new Error('Hooks can only be created within React.withHooks factory');
        }
        (defer ? deferredHooks : hooks).push(factory)
      },
      captureHooks(fn) {
        if (hooks) { throw new Error('Already capturing hooks'); }
        hooks = [];
        deferredHooks = [];
        let value, combinedHooks;
        try {
          value = fn();
          combinedHooks = [...hooks, ...deferredHooks];
        } catch (e) {
          throw e;
        } finally {
          hooks = deferredHooks = undefined;
        }
        return { value, hooks: combinedHooks };
      },
    };
  })();

  function withDisplayName(displayName, fn) {
    return (displayName ? Object.assign(fn, { displayName }) : fn);
  }

  function createHook({ defer, factory, fallback }) {
    if (Lifecycle.isRenderPhase()) {
      throw new Error('Attempting to create hook within React.withHooks render function');
    }
    if (!Lifecycle.isFactoryPhase()) {
      console.warn('Deprecation notice: prefer React.withHooks to declaring hooks within a render function');
      return fallback();
    }
    const { instance, render } = factory();
    Lifecycle.registerHook(render, { defer });
    return instance;
  }

  React.createHook = (factory) => {
    return createHook({
      defer: false,
      factory: () => {
        const PENDING = {};
        let currentValue = PENDING;
        const instance = new Proxy({}, {
          get(self, key) {
            if (Lifecycle.isFactoryPhase() || (currentValue === PENDING)) {
              throw new Error('Attempting to retrieve uninitialized custom hook value');
            }
            if (!Lifecycle.isRenderPhase() && !Lifecycle.isCallbackPhase()) {
              throw new Error('Attempting to retrieve custom hook value outside React.withHooks render function');
            }
            return currentValue[key];
          }
        });
        const render = factory();
        return {
          instance,
          render(props) {
            const value = render(props);
            if ((value !== undefined) && !(isPlainObject(value) || Array.isArray(value))) {
              throw new Error('Only plain objects or arrays are allowed for custom hook values');
            }
            currentValue = value;
          },
        }
      },
      fallback: () => {
        throw new Error('Custom hooks created with React.createHook can only be used within React.withHooks factory');
      }
    })
  }

  function isPlainObject(value) {
    return (typeof value === 'object') && (value !== null) && (!value.constructor || (value.constructor === Object));
  }

  React.withHooks = (factory) => withDisplayName(factory.name,
    (props) => {
      // N.B. This implementation will reinvoke the factory on every render, which is undesirable.
      // The following commented-out implementation fixes that, however it exposes an internal React
      // bug which causes the app to crash in some scenarios.
      const { render, hooks } = Lifecycle.withPhase(PHASE_FACTORY, () => {
        const { hooks, value: render } = Lifecycle.captureHooks(factory);
        return { hooks, render };
      })();
      return Lifecycle.withPhase(PHASE_RENDER, () => {
        hooks.forEach((hookFactory) => { hookFactory(props); });
        return render(props);
      })();
    }
  );
  /*
  React.withHooks = (factory) => withDisplayName(factory.name, Lifecycle.withPhase(PHASE_RENDER,
    (props) => {
      const { hooks: hookFactories, value: render } = useMemo(
        Lifecycle.withPhase(PHASE_FACTORY, () => Lifecycle.captureHooks(factory)),
        []
      );
      hookFactories.forEach((hookFactory) => { hookFactory(props); });
      return render(props);
    }
  ));
  */

  const useState = React.useState;
  React.useState = (initialValue) => createHook({
    defer: false,
    factory: () => {
      const PENDING = {};
      let currentValue = PENDING;
      let setValue = (value) => {
        throw new Error('Attempting to update uninitialized state value');
      };
      const instance = [currentValue, (value) => setValue(value)];
      Object.defineProperty(instance, '0', {
        get() {
          if (Lifecycle.isFactoryPhase() || (currentValue === PENDING)) {
            throw new Error('Attempting to retrieve uninitialized state hook value');
          }
          if (!Lifecycle.isRenderPhase() && !Lifecycle.isCallbackPhase()) {
            throw new Error('Attempting to retrieve state hook value outside React.withHooks render function');
          }
          return currentValue;
        },
      });
      return {
        instance,
        render(props) {
          const value = (
            typeof initialValue === 'function' ? () => initialValue(props) : initialValue
          );
          const hook = useState(value);
          currentValue = hook[0];
          setValue = hook[1];
        },
      };
    },
    fallback: () => useState(initialValue),
  });

  const useEffect = React.useEffect;
  React.useEffect = (fn, dependencies) => createHook({
    defer: true,
    factory: () => {
      return {
        instance: undefined,
        render(props) {
          useEffect(
            Lifecycle.createCallback(() => {
              const cleanup = fn(props);
              return cleanup && Lifecycle.createCleanup(cleanup);
            }),
            dependencies && dependencies(props)
          );
        },
      };
    },
    fallback: () => useEffect(fn, dependencies),
  });

  const useMemo = React.useMemo;
  React.useMemo = (factory, dependencies) => createHook({
    defer: false,
    factory: () => {
      const PENDING = {};
      let currentValue = PENDING;
      const instance = () => {
        if (currentValue === PENDING) { throw new Error('Attempting to retrieve uninitialized memo value'); }
        return currentValue;
      };
      return {
        instance,
        render(props) {
          currentValue = useMemo(
            Lifecycle.createCallback(() => factory(props)),
            dependencies(props)
          );
        },
      }
    },
    fallback: () => useMemo(factory, dependencies),
  });

  const useCallback = React.useCallback;
  React.useCallback = (factory, dependencies) => createHook({
    defer: false,
    factory: () => {
      let currentValue = undefined;
      const instance = (...args) => {
        if (!currentValue) { throw new Error('Attempting to call uninitialized callback'); }
        return currentValue(...args);
      };
      return {
        instance,
        render(props) {
          currentValue = useCallback(
            Lifecycle.createCallback((...args) => factory(props)(...args)),
            Array.isArray(dependencies) ? dependencies : dependencies(props)
          );
        },
      }
    },
    fallback: () => useCallback(factory, dependencies),
  });

  const useRef = React.useRef;
  React.useRef = (factory) => createHook({
    defer: false,
    factory: () => {
      let currentValue = undefined;
      const instance = Object.defineProperty({}, 'current', {
        get() {
          if (!currentValue) { throw new Error('Attempting to retrieve uninitialized ref'); }
          return currentValue.current;
        },
        set(value) {
          if (!currentValue) { throw new Error('Attempting to update uninitialized ref'); }
          return (currentValue.current = value);
        },
      });
      return {
        instance,
        render(props) {
          currentValue = useRef(factory(props));
        },
      }
    },
    fallback: () => useRef(factory),
  });
}

function require(imports) {
  return Promise.all(imports.map(({ src, dependencies }) => loadModule(src, dependencies)));

  function loadModule(src, dependencies) {
    return fetch(src).then((result) => {
      if (!result.ok) { throw new Error('Network error'); }
      return result.text();
    }).then((source) => {
      const moduleFactory = eval(`(function (global, module, exports, require) {${source}})`);
      return evaluateModule(moduleFactory, dependencies);
    });
  }

  function evaluateModule(fn, dependencies) {
    const global = window;
    const module = { exports: {} };
    const exports = module.exports;
    function require(id) {
      if (id in dependencies) { return dependencies[id]; }
      throw new Error(`Module not found: ${id}`);
    }
    fn(global, module, exports, require);
    return module.exports;
  }
}

              
            
!
999px

Console