Created
August 15, 2020 22:01
-
-
Save abelsan/7f1485396de8bca05beeda8a074bbd97 to your computer and use it in GitHub Desktop.
Synchronization of data between parent and child react components
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="stats.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(countRef.current); | |
console.log('child: ' + countRef.current); | |
}, props.interval); | |
// cleanup | |
return () => { | |
clearTimeout(timeout); | |
} | |
}, [counter]); | |
return ( | |
<> | |
<div>In child counter: {counter}</div> | |
</> | |
); | |
} | |
const Stats = () =>{ | |
const [stats, updateStats] = React.useState(0); | |
function parent(counter){ | |
const inspect = updateStats(counter); | |
console.log('parent: ' + counter); | |
} | |
return ( | |
<div> | |
<div>In parent stats: {stats}</div> | |
<Counter | |
start="0" | |
increment="2" | |
interval="2000" | |
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