Skip to content

React components using generator functions*, using new Hooks API

License

Notifications You must be signed in to change notification settings

askbeka/react-hooker-gene

Repository files navigation

React hooker generator

npm install react-hooker-gene

Importing library

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'

Motivation

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.

Example usage

Simple

export const Component = wrapper(function* () {
  const [state, useState] = yield useState();
  
  return (
    <div>
      {state}
    </div>
  );
});

seems like javascript

With custom hook using generator

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>
  );
});

Wrap existing hooks

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>
  );
});

Resources

About

React components using generator functions*, using new Hooks API

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published