Last active
June 18, 2020 20:15
-
-
Save sandeshdamkondwar/4ec6a1b909ff745e4cb7928ef7c33b75 to your computer and use it in GitHub Desktop.
useMemo hook for avoiding unnecessary renderings of child components
This file contains hidden or 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 React, { useState, useMemo } from 'react' | |
function Counter() { | |
const [counterOne, setCounterOne] = useState(0) | |
const [counterTwo, setCounterTwo] = useState(0) | |
const incrementOne = () => { | |
setCounterOne(counterOne + 1) | |
} | |
const incrementTwo = () => { | |
setCounterTwo(counterTwo + 1) | |
} | |
const isEven = useMemo(() => { | |
let i = 0 | |
while (i < 2000000000) i++ | |
return counterOne % 2 === 0 | |
}, [counterOne]) | |
return ( | |
<div> | |
<div> | |
<button onClick={incrementOne}>Count One - {counterOne}</button> | |
<span>{isEven ? 'Even' : 'Odd'}</span> | |
</div> | |
<div> | |
<button onClick={incrementTwo}>Count Two - {counterTwo}</button> | |
</div> | |
</div> | |
) | |
} | |
export default Counter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment