Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.

React fetch hook

Jan 30, 2021

DESCRIPTION

Let's create a custom hook for fetching data with the browser fetch which we'll use for getting some Pokemons from pokeAPI.

Preview

Fetch them all!

React - useFetch.js
React - App.js

Summary

  • We used a combination of useReducer and useEffect hooks to create our custom useFetch hook.
  • Additionally, browser fetch with async/await and try...catch was used to get the data from an API through an endpoint.
  • Then, we created an example application using pokeAPI and Material UI.
  • As fetch requires a little bit of boilerplate and doesn't catch all the possible errors (need to use .ok check), you might consider axios instead for the useFetch hook (and call it e.g. useApi 😀)
  • There is a way to completely omit this custom hook by using react-query 🙈. It's an amazing library for data fetching with support for cache, etc.
  • I didn't mention Redux or MobX at all, as over time I value decentralized state more and there are solutions like react-query for data fetching. Still, you could use any of these two if you're experienced with them instead of the custom hook we created.
  • Feel free to extend the app as you need - maybe create astonishing Pokedex online? (just throwing an idea)
logo with a rocket of the BigDevSoon application

Level up your Frontend skills

Code real-world projects based on Figma designs.
spread the word
Did you like this post? Share it with the world! 🌐