When to use useEffect?

后端 未结 3 1577
温柔的废话
温柔的废话 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 08:29

    You showed two different examples,

    handleButtonClick fires on Button 1 click, while useEffect fires on every state change state (according to the dependency array).

    In the next example, you notice that useEffect will log on every button click (Button 1/2), and handleButtonClick will log only on Button 2 click.

    import React, { useState, useEffect } from "react";
    
    function Example() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        console.log(`You rendered ${count} times`);
      }, [count]);
    
      const handleButtonClick = () => {
        setCount(count + 1);
        console.log(`You clicked ${count + 1} times`);
      };
    
      return (
        

    You clicked {count} times

    ); }

    Refer to useEffect docs

提交回复
热议问题