Skip to content

Instantly share code, notes, and snippets.

@sandeshdamkondwar
Last active June 18, 2020 20:15
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 sandeshdamkondwar/4ec6a1b909ff745e4cb7928ef7c33b75 to your computer and use it in GitHub Desktop.
Save sandeshdamkondwar/4ec6a1b909ff745e4cb7928ef7c33b75 to your computer and use it in GitHub Desktop.
useMemo hook for avoiding unnecessary renderings of child components
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