When to use useEffect?

后端 未结 3 1571
温柔的废话
温柔的废话 2021-02-05 07:49

I\'m currently looking at the react doc\'s example for useEffect

import React, { useState, useEffect } from \'react\';

function Example() {
  const [count, setC         


        
3条回答
  •  半阙折子戏
    2021-02-05 08:05

    The idea to use useEffect hook is to execute code that needs happens during lifecycle of the component instead of on specific user interactions or DOM events.

    For instance, you wish to set a timer that executes a code when the component is rendered initially or as done in your initial example, the document title is updated when the component mounts, there is no user interaction associated here

    useEffect is an alternative for lifecycle method in class components in a functional component. It can be used to execute actions when the component mounts, or certain prop or state updated for component as well as to execute code when the component is about to unmount

提交回复
热议问题