Just started using React function hooks. I was looking into a case where you have a parent function which passes an array and a child function which relies on the array contents.
App.js (parent) ->
import React, {useEffect} from 'react';
import ChartWrapper from './StaticChart/ChartWrapper';
import './App.css';
function App() {
let data = [];
function newVal() {
let obj = null;
let val = Math.floor(Math.random() * 10);
let timeNow = Date.now();
obj = {'time': timeNow, 'value': val};
data.push(obj);
// console.log(obj);
}
useEffect(
() => {
setInterval(() => {newVal();}, 500);
}, []
);
return (
<div className="App">
<ChartWrapper data={data} />
</div>
);
}
export default App;
ChartWrapper.js (child) ->
import React, {useRef, useEffect} from 'react';
export default function ChartWrapper(props) {
const svgRef = useRef();
const navRef = useRef();
useEffect(
() => {
console.log('function called');
}, [props.data]
);
return (
<div>
<svg ref = {svgRef} width = {700} height = {400}></svg>
<svg ref = {navRef} width = {700} height = {75}></svg>
</div>
);
}
So every time App.js adds a new object in the array, ChartWrapper gets called. Currently, in the ChartWrapper function, I have useEffect which should listen to changes in props.data array and get executed, but it is not working. The only time the function gets called is initially when the component renders.
What am I doing wrong?
[JSON.stringify(props.data)]and see if it works the way you want. Btw, that probably isn't a great solution, just a way of illustrating what's going on.data.push(obj)withdata = [...data, obj]useEffectto re-run on every render, since the array will always be different.dataevery 500ms, right? I presume we wantuseEffectto run every timedatachanges.