Skip to content

Instantly share code, notes, and snippets.

@abelsan
Created August 15, 2020 22:01
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 abelsan/7f1485396de8bca05beeda8a074bbd97 to your computer and use it in GitHub Desktop.
Save abelsan/7f1485396de8bca05beeda8a074bbd97 to your computer and use it in GitHub Desktop.
Synchronization of data between parent and child react components
<!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>
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