UNPKG

1.94 kBJavaScriptView Raw
1import { useState as _useState, useReducer as _useReducer, useRef as _useRef, useEffect as _useEffect, useImperativeHandle as _useImperativeHandle, useLayoutEffect as _useLayoutEffect, useCallback as _useCallback, useMemo as _useMemo, useContext as _useContext, useDebugValue as _useDebugValue, useErrorBoundary as _useErrorBoundary, } from "preact/hooks";
2import { HydrateContext } from "./hydrate.js";
3const hooks = new WeakMap();
4const warn = (name, hook, result) => {
5 console.error(new Error(`A non-hydrated component attempted to invoke "${name}".\n\nWrap this component in the "withHydrate" HOC (exported by "microsite/hydrate") to enable interactivity at compile time.`));
6 hooks.set(hook, result);
7 return result;
8};
9function wrapHook(name, hook) {
10 function wrappedHook(...args) {
11 const hydrated = _useContext(HydrateContext);
12 if (!hydrated) {
13 if (hooks.has(hook))
14 return hooks.get(hook);
15 return warn(name, hook, hook.apply(null, args));
16 }
17 return hook.apply(null, args);
18 }
19 Object.defineProperty(wrappedHook, "name", {
20 value: name,
21 configurable: true,
22 });
23 return wrappedHook;
24}
25export const useState = wrapHook("useState", _useState);
26export const useReducer = wrapHook("useReducer", _useReducer);
27export const useRef = wrapHook("useRef", _useRef);
28export const useEffect = wrapHook("useEffect", _useEffect);
29export const useImperativeHandle = wrapHook("useImperativeHandle", _useImperativeHandle);
30export const useLayoutEffect = wrapHook("useLayoutEffect", _useLayoutEffect);
31export const useCallback = wrapHook("useCallback", _useCallback);
32export const useMemo = wrapHook("useMemo", _useMemo);
33export const useContext = wrapHook("useContext", _useContext);
34export const useDebugValue = wrapHook("useDebugValue", _useDebugValue);
35export const useErrorBoundary = wrapHook("useErrorBoundary", _useErrorBoundary);