Skip to content

Instantly share code, notes, and snippets.

@izabellewilding
Created April 11, 2022 20:57
Show Gist options
  • Save izabellewilding/c85e3e31570bfd7e7f38bf6f55d3c966 to your computer and use it in GitHub Desktop.
Save izabellewilding/c85e3e31570bfd7e7f38bf6f55d3c966 to your computer and use it in GitHub Desktop.
import "./styles.css";
import { useCallback, useEffect, useState } from "react";
const SubComponent = ({ handleClick, isRed }) => {
useEffect(() => {
const interval = setInterval(() => {
handleClick(!isRed);
}, 1000);
return () => clearInterval(interval);
}, [handleClick, isRed]);
return (
<button style={{ backgroundColor: isRed && "red" }} onClick={handleClick}>
Change my colour
</button>
);
};
const ParentComponent = () => {
const [red, setRed] = useState(false);
const [counter, setCount] = useState(0);
const handleClick = useCallback((isRed) => setRed(isRed), [setRed]);
useEffect(() => {
const interval = setInterval(() => {
setCount(counter + 1);
}, 100);
return () => clearInterval(interval);
}, [setCount, counter]);
return (
<div>
{counter}
<SubComponent isRed={red} handleClick={handleClick} />;
</div>
);
};
export default function App() {
return (
<div className="App">
<ParentComponent />
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment