1

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.

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

Comments

0

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.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<body>
  <div id="container">
  </div>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.