skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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.

    export default function MyComponent(props: any): ReactElement {
      const {dataFromApi, setDataFromApi} = useState();
    
      useEffect(() => {
        // Executed once on component initialization
        getData();
      },[])
    
      function getData() {
         fetch(url)
            .then((response) => response.json())
            .then((json) => {
                setDataFromApi(json);
            });
      }
    
    
      return (
       <div><button onclick={getData}></button></div>
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search