最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactJS useEffect() is running every time on page load - Stack Overflow

programmeradmin1浏览0评论

My useEffect() is running every time at page load. I want it to run after I click a button. My code is as follows :

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


const HooksDemo = () => {

    const [myArray, setMyArray] = useState([]);

    useEffect(() => {
        if(myArray) {
            console.log("My Array    : ",myArray)
        }
    } , [myArray])


       const populateArray = () => {
           var sampleData = [
               { id: 1, name: "Carl" },
               { id: 2, name: "Negan" },
               { id: 3, name: "Daryl" }
           ];

           setMyArray(sampleData);
       }


    return (
        <div>
       
            <button onClick={populateArray}> Populate Array </button>
        
        </div>
    );
};

export default HooksDemo;

I want to print myArray in console after I populate it using the populateArray() function but the useEffect() function is running at page load as well as after the execution of populateArray() function.

My useEffect() is running every time at page load. I want it to run after I click a button. My code is as follows :

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


const HooksDemo = () => {

    const [myArray, setMyArray] = useState([]);

    useEffect(() => {
        if(myArray) {
            console.log("My Array    : ",myArray)
        }
    } , [myArray])


       const populateArray = () => {
           var sampleData = [
               { id: 1, name: "Carl" },
               { id: 2, name: "Negan" },
               { id: 3, name: "Daryl" }
           ];

           setMyArray(sampleData);
       }


    return (
        <div>
       
            <button onClick={populateArray}> Populate Array </button>
        
        </div>
    );
};

export default HooksDemo;

I want to print myArray in console after I populate it using the populateArray() function but the useEffect() function is running at page load as well as after the execution of populateArray() function.

Share Improve this question asked Nov 5, 2020 at 8:06 Niko BellicNiko Bellic 591 gold badge2 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

That's the normal behavior of the useEffect hook.
You can add your own logic determening when it should or should not call a function at page load, like by checking if the array is empty or not.

useEffect(() => {
  if(myArray.length > 0) {
    console.log("My Array    : ",myArray)
  }
} , [myArray])

You can utilize the useRef hook, keep the original array reference in the ref container so that on every re-render the initial value is retained.

Then place a check in the useEffect callback so that it only runs when the array reference changes on every state change:

const {useState, useEffect, useRef} = React;

const HooksDemo = () => {
  const [myArray, setMyArray] = useState([]);
  const myArrayRef = useRef(myArray);
  useEffect(() => {
    if (myArray !== myArrayRef.current) {
      console.log("My Array    : ", myArray);
    }
  }, [myArray, myArrayRef]);

  const populateArray = () => {
    var sampleData = [
      { id: 1, name: "Carl" },
      { id: 2, name: "Negan" },
      { id: 3, name: "Daryl" }
    ];

    setMyArray(sampleData);
  };

  return (
    <div>
      <button onClick={populateArray}> Populate Array </button>
      {}
    </div>
  );
};
ReactDOM.render(<HooksDemo/>, document.querySelector("#container"));
<script crossorigin src="https://unpkg./react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg./react-dom@17/umd/react-dom.development.js"></script>
<body>
  <div id="container">
  </div>
</body>

发布评论

评论列表(0)

  1. 暂无评论