I can not fulfill all the conditions:
- I need some function inside
useCallback, because I set it as props to child component (for re-render preventing) - I need to use
debounce, because my function is "end point" and can be called ~100times/sec - I need to get current (actual values) after debounce.
I have problem with last point, my values after debounce (1000ms) is outdated.
How to get current values using useCallback + debounce ? (values in alert must to be same as page)
//ES6 const, let
//ES6 Destructuring
const { Component, useCallback, useState, useEffect } = React;
const SUBChildComponent = (props) => (<button onClick={props.getVal}>GetValue with debounce</button>);
const ChildComponent = () => {
// some unstable states
const [someVal1, setSomeVal1] = useState(0);
const [someVal2, setSomeVal2] = useState(0);
const [someVal3, setSomeVal3] = useState(0);
// some callback witch works with states AND called from subClild components
const getVal = useCallback(_.debounce(() => {
alert(`${someVal1}\n${someVal2}\n${someVal3}`);
}, 1000), [someVal1, someVal2, someVal3]);
// some synthetic changes
useEffect(() => {
const id = setInterval(() => setSomeVal1(someVal1 + 1), 50);
return () => clearInterval(id);
}, [someVal1]);
// some synthetic changes
useEffect(() => {
const id = setInterval(() => setSomeVal2(someVal2 + 1), 100);
return () => clearInterval(id);
}, [someVal2]);
// some synthetic changes
useEffect(() => {
const id = setInterval(() => setSomeVal3(someVal3 + 1), 250);
return () => clearInterval(id);
}, [someVal3]);
return <React.Fragment><SUBChildComponent getVal={getVal}/><br/>{someVal1}<br/>{someVal2}<br/>{someVal3}
</React.Fragment>;
};
class App extends Component {
render() {
return (<div><ChildComponent/></div>);
}
}
ReactDOM.render(<App/>, document.querySelector(".container"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>
<div class="container"></div>
