Created
December 10, 2020 22:23
-
-
Save shrimpy/768a245ea394d7a52eef5a049327f29e to your computer and use it in GitHub Desktop.
Reactjs: useCallback and React.memo fun - code - 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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