npm install react-hooker-gene
You can import the generated bundle to use the whole library generated by this starter:
import wrapper, { useState, useEffect } from 'react-hooker-gene'
Additionally, you can import the transpiled modules from dist/lib
in case you have a modular library:
import wrapper, { useState, useEffect } from 'react-hooker-gene/dist/lib/react-hooker-gene'
React Hooks API allows us to use functions for impure components, but it is hard to test those functions in isolation, and the order of execution of hooks too, since it is important in order for React to function well.
export const Component = wrapper(function* () {
const [state, useState] = yield useState();
return (
<div>
{state}
</div>
);
});
seems like javascript
function* useGithubUsers() {
const [query, setQuery] = yield useState("");
const [results, setResults] = yield useState([]);
const [loading, setLoading] = yield useState(false);
// each rerender
yield useEffect(debounce(() => {
if (query !== "") {
setLoading(true);
fetch(`https://api.github.com/search/users?q=${query}`, { method: "GET"}).then(req => {
return req.json();
}).then(data => {
setLoading(false)
setResults(data.items)
})
}
}, 300), [query]);
return {
query,
setQuery,
setLoading,
results,
loading,
};
}
export const App = genWrapper(function* () {
const { setQuery, query, results, loading } = yield* useGithubUsers();
return (
<div>
<input onChange={e => setQuery(e.target.value)} />
<ul>
{loading && <li>Loading</li>}
{
results && results.map((item, index) => <li key={index} >{item.login}</li>)
}
</ul>
</div>
);
});
import { makeHook, useState } from 'react-hooker-gene';
import someCustomHook from 'some-custom-hook';
const validCustomHook = (...args) => makeHook(someCustomHook, args)
export const Component = wrapper(function* () {
const [state, useState] = yield useState();
yield validCustomHook(/* does something */);
return (
<div>
{state}
</div>
);
});