Skip to content

Instantly share code, notes, and snippets.

@lilactown
Last active November 6, 2018 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lilactown/24847babed9685357e2320df39821fbb to your computer and use it in GitHub Desktop.
Save lilactown/24847babed9685357e2320df39821fbb to your computer and use it in GitHub Desktop.
Reconciler-agnostic React hooks
/**
Problem 1: As a library developer, I want to be able to test my hooks without having to render a component.
Problem 2: As a library developer, I want to be able to publish my hooks without a direct dependency on React.
Problem 3: As an application developer, I want to be able to easily override (with some sort of proxy/rewire magic,
perhaps) hooks with side effects in tests.
Problem 4: As an application developer, I would like to be able to use hooks written for React in other frameworks
that support hooks.
Problem 5: As an application developer, I would like to better communicate to other developers on my team what
function calls are Hooks vs. "regular" functions.
Solution: Create a `use` function that, when called, injects custom hooks with a context object with appropriate
native Hooks.
**/
import * as React from 'react';
import { render } from "react-dom";
// a single entry point to proxy/rewire
function use(customHook, ...params) {
customHook(React, ...params);
}
// simple, unneeded example
function state({ useState }, initial) {
return useState(initial);
}
// custom hook
function documentTitle({ useEffect }, title) {
useEffect(() => {
document.title = title;
}, [title])
}
// Usage
function App() {
return <NestedComponent />;
}
function NestedComponent() {
const [value, setValue] = use(state, "page title");
use(documentTitle, value);
return (
<div>
<input value={value} onChange={e => setValue(e.target.value)} />
</div>
);
}
render(<App />, window.root);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment