When to use useEffect?

后端 未结 3 1568
温柔的废话
温柔的废话 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
    2021-02-05 08:20

    Please refer below content for more clarity. You might have missed reading that after copying code from official document.

    Example Using Hooks

    What does useEffect do?

    By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.

    Why is useEffect called inside a component?

    Placing useEffect inside the component lets us access the count state variable (or any props) right from the effect. We don’t need a special API to read it — it’s already in the function scope. Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.

    Does useEffect run after every render?

    Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

提交回复
热议问题