React Hooks to Fetch Data
We have learned about the life cycle methods we need to use for fetching data and how to fix the infinite loop when updating the state in the
componentDidUpdate()
method.In early 2019, React 16.8 was released with a stable release of React Hooks. As we discussed in the Chapter 15, Promise API and async/await.
React Hooks allows us to use state and other features in the function components without writing a class. In this section, we are going to learn how to use React Hooks to refactor what we have done in the previous sections, such as fetching data or updating the state by clicking on either the
Popularity
orTrending
buttons.In the class-based components, we have used the
componentDidMount()
method to initially fetch data, and thecomponentDidUpdate()
method to re-fetch data upon re-rendering. To avoid the infinite loop, we usedprevProps
to compare whether the previous prop is the same as the current prop.With
useEffect
, we can do both initial requests and...