Skip to main content

Build react useFetch from scratch | with check list, tests and examples

In this video CJ shows how to implement a useFetch react hook from scratch. He shows how to manage data and loading state. He also shows how to handle fetch errors, parse errors and request cancellations. He provides a test suite, checklist and examples so you can practice implementing this hook yourself.

View the code here: https://github.com/w3cj/use-x


00:00 intro
03:14 repo setup
03:30 example hook usage
04:46 repo walk-through
05:00 test setup
05:40 stubbed implementation
06:03 call fetch on mount
06:46 manage loading state
09:11 manage data state
10:41 handle options immediate
12:30 handle re-renders
16:09 handle empty url
17:41 handle fetch errors
19:12 handle json parse error
19:38 handle update calls
21:12 handle abort error
23:18 resetting state on load
24:30 handle multiple requests
28:53 cancel request on unmount
30:00 thanks!

Corrections:
19:29 The test "should handle http errors correctly" has been added to the repo since video release. See notes in src/use-fetch/README.md.

React custom hooks | https://react.dev/learn/reusing-logic-with-custom-hooks usehooks | https://usehooks.com/ usehooks-ts | https://usehooks-ts.com/ react-use | https://github.com/streamich/react-use beautiful-react-hooks | https://github.com/antonioru/beautiful-react-hooks Fetch API | https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API RequestInit | https://developer.mozilla.org/en-US/docs/Web/API/RequestInit AbortError Example | https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal#aborting_a_fetch_operation_with_a_timeout Response ok | https://developer.mozilla.org/en-US/docs/Web/API/Response/ok