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