Created
August 16, 2020 01:36
-
-
Save abelsan/d170ffa960c6cebf47766320c44fadc5 to your computer and use it in GitHub Desktop.
holding state in variable outside component
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title>Clock</title> | |
<!-- don't use this in production: --> | |
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> | |
</head> | |
<body> | |
<h1 style="font-family: Arial;">counters</h1> | |
<!-- target div --> | |
<div id="root"></div> | |
<!-- load react --> | |
<script | |
src="https://unpkg.com/react/umd/react.development.js" | |
crossorigin | |
></script> | |
<script | |
src="https://unpkg.com/react-dom/umd/react-dom.development.js" | |
crossorigin | |
></script> | |
<!-- react component. --> | |
<script src="index.js" defer type="text/babel"></script> | |
</body> | |
</html> |
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
const Counter = (props) => { | |
const [counter, setCounter] = React.useState(Number(props.start)); | |
// useRef to avoid the closure in the timer | |
const countRef = React.useRef(counter); | |
countRef.current = counter; | |
// timer | |
React.useEffect(() => { | |
const timeout = setTimeout(() => { | |
setCounter(counter + Number(props.increment)); | |
props.parent({['counter'+props.label]: countRef.current}); | |
console.log(`child-${props.label}: ${countRef.current}`); | |
}, props.interval); | |
// cleanup | |
return () => { | |
clearTimeout(timeout); | |
} | |
}, [counter]); | |
return ( | |
<> | |
Child-{props.label}: {counter} | |
</> | |
); | |
} | |
let myState = {counter01:0, counter02:0, counter03:0}; | |
const Stats = () =>{ | |
const [stats, updateStats] = React.useState(null); | |
function parent(counter){ | |
const merged = {...myState, ...counter} | |
myState = merged; | |
updateStats(merged); | |
console.log('parent: ' + JSON.stringify(counter)); | |
} | |
return ( | |
<div> | |
Parent: {JSON.stringify(stats)},<br/> | |
<Counter | |
label="01" | |
start="0" | |
increment="2" | |
interval="5000" | |
parent={parent} />, | |
<Counter | |
label="02" | |
start="0" | |
increment="10" | |
interval="2000" | |
parent={parent} />, | |
<Counter | |
label="03" | |
start="0" | |
increment="5" | |
interval="3000" | |
parent={parent} /> | |
</div> | |
) | |
} | |
ReactDOM.render( | |
<Stats />, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment