/nuclio-custom-react-hooks

Source code of custom react hooks at Nuclio Digital School

Primary LanguageJavaScript

nuclio-custom-react-hooks

Source code of custom react hooks masterclass at Nuclio Digital School.

preview

Setup

git clone https://github.com/papeloto/nuclio-custom-react-hooks.git
cd nuclio-custom-react-hooks
yarn install
yarn start

Ideas

  • Even thought hooks are functions they behave differently
  • Hooks are subscriptions to events
  • Hooks have rules like starting by use or not calling them conditionally
  • We can define our custom hooks to encapsulate logic
  • If your custom hook doesn't use the built-in hooks, it is probably a function, not a hook.
  • We can use libraries like axios for making fetching easier

Tasks

You will find the solutions of these tasks in different branches.

  1. Add check feature with its according update request
  2. Use axios' instances to clean up requests
  3. Do proper error checking on request
  4. Trust the request and rollback if they don't succeed
  5. Refactor to React context with its custom useTasks hook.

That way we can make our components more isolated. Going from this:

export const Controls = ({ onLoad, tasks }) => (
    <footer>
        <div>
            <strong>{tasks.filter((task) => !task.completed).length}</strong> tasks left.
        </div>
        <button onClick={onLoad}>Load More</button>
    </footer>
);

To this:

export const Controls = () => {
    const { tasks, loadMore } = useTasks();

    return (
        <footer>
            <div>
                <strong>{tasks.filter((task) => !task.completed).length}</strong> tasks left.
            </div>
            <button onClick={loadMore}>Load More</button>
        </footer>
    );
};
  1. Use some cool react data fetching library such as react-query or swr