I have a React component in my application that fetches data from an API in its componentDidMount lifecycle method. However, I also need to ensure that the component re-renders whenever the fetched data changes. What would be the best approach to achieve this, and could you provide some code examples to illustrate the solution?
I’ve considered using various techniques such as setting state in the component’s componentDidMount method, using hooks like useState and useEffect, or employing libraries like Redux for managing the component’s state. However, I’m unsure which approach would be the most efficient and maintainable in this scenario.
2
Answers
First, It is recommended to use React Functional Components instead of Class components
Second, Check this link from React Docs that illustrates how to do data fetch inside
useEffect
Third, If you are to use Redux, My advice is to use Redux Toolkit and RTK Query.
RTK Query provides hooks for you to fetch data
You can try something like this, with hooks, that will fetch the API when the component is created, then set the new state when you call the API again.