Where can I make API call with hooks in react?

前端 未结 5 1366
有刺的猬
有刺的猬 2020-11-27 14:43

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

     componentDidMount(){
          //He         


        
5条回答
  •  天命终不由人
    2020-11-27 15:20

    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 these side effects, the component will re-render.

    Example from the docs.

    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 (
        

    You clicked {count} times

    ); }

    For example, you could call setCount in a callback function of an async request. When the callback is executed, the state will get updated and React will re-render the component. Also from the docs:

    Tip

    If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

提交回复
热议问题