Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  25] [ 7]  / answers: 1 / hits: 9131  / 4 Years ago, thu, november 5, 2020, 12:00:00

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.


More From » reactjs

 Answers
5

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])

[#2362] Friday, October 30, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keric

Total Points: 572
Total Questions: 93
Total Answers: 97

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
keric questions
;