Created
April 11, 2022 20:57
-
-
Save izabellewilding/c85e3e31570bfd7e7f38bf6f55d3c966 to your computer and use it in GitHub Desktop.
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
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