Where can I make API call with hooks in react?

1462 views javascript
2

Basically we do API calls in componentDidMount() life cycle method in React class components like below

     componentDidMount(){
          //Here we do API call and do setState accordingly
     }

But after hooks are introduced in React v16.7.0, there are no more class components.

My query is, where exactly do we need to make API call in functional component with hooks?

Do we have any method for it similar like componentDidMount()?

answered question

2 Answers

5

Do we have any method for it similar like componentDidMount()?

useEffect() method is similar to componentDidMount() and componentDidUpdate()


According to Using the Effect Hook:

The Effect Hook lets you perform side effects in function components

import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

posted this
3

When you are using functional components with the hooks API, you can use the useEffect() method to produce side effects. Whenever the state is updated because of hese side effects, the component will re-render.

posted this

Have an answer?

JD

Please login first before posting an answer.