Skip to content

Instantly share code, notes, and snippets.

@shrimpy
Created December 10, 2020 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shrimpy/768a245ea394d7a52eef5a049327f29e to your computer and use it in GitHub Desktop.
Save shrimpy/768a245ea394d7a52eef5a049327f29e to your computer and use it in GitHub Desktop.
Reactjs: useCallback and React.memo fun - code - 1
let _int_val = 0;
const IntValComp = React.memo(({initFunc}) => {
const [value, setValue] = React.useState(-1);
// expect to init value once only
React.useEffect(
() => {
const val = _int_val++;
if (_int_val >= 100000) _int_val = 0;
setValue(val);
initFunc(val);
},
[initFunc],
);
return <div>{`int value zero: ${value}`}</div>;
});
const ParentComp = () => {
const [intVal, setIntVal] = React.useState();
const updateValue = React.useCallback((v) => setIntVal(v), []);
return (
<div>
<IntValComp initFunc={updateValue} />
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment