Skip to content

Instantly share code, notes, and snippets.

@getify
Last active February 5, 2019 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save getify/52706820ef7a7264928e5124ba079a70 to your computer and use it in GitHub Desktop.
Save getify/52706820ef7a7264928e5124ba079a70 to your computer and use it in GitHub Desktop.
React's `useCallback(..)` memoization... how does it work?
function Foo() {
var [x,setX] = useState(0);
var [y,setY] = useState(1);
var cb = useCallback(
function printXYIfChanged() { console.log(x,y); },
[x,y]
);
useEffect(
function pollingXY(){
var intv = setInterval(cb,100);
return function clearPolling() { clearInterval(intv); };
},
[x,y]
);
return (
<>
<button onClick={()=>setX(x=>++x)}>inc x</button>
<button onClick={()=>setY(y=>++y)}>inc y</button>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment