Created
March 30, 2020 04:53
-
-
Save yue4u/ac0a88a45ad1016ed038d848d3ed525b 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 React, { memo, useMemo, useState, useCallback } from 'react'; | |
const Child = ({ | |
index, | |
decrease, | |
}: { | |
index: number; | |
decrease: () => void; | |
}) => { | |
const [state, setState] = useState(0); | |
console.log(`${index} rerender`); | |
return ( | |
<div> | |
<p>child:{state}</p> | |
<button onClick={decrease}>decrease</button> | |
<button onClick={() => setState(state + 1)}>rerender this</button> | |
</div> | |
); | |
}; | |
const MemoizedChild = memo(Child); | |
export default function Parent() { | |
const [count, setCount] = useState(0); | |
const increase = () => setCount(count => count + 1); | |
const decrease = () => setCount(count => count - 1); | |
const decreaseCallback = useCallback(() => decrease(), []); | |
const UseMemoChild1 = useMemo(() => <Child index={5} decrease={decrease} />, [ | |
decrease, | |
]); | |
const UseMemoChild2 = useMemo( | |
() => <Child index={6} decrease={decreaseCallback} />, | |
[decreaseCallback], | |
); | |
return ( | |
<main> | |
<p>Count {count}</p> | |
<button onClick={increase}>+</button> | |
<Child index={1} decrease={decrease} /> | |
<Child index={2} decrease={decreaseCallback} /> | |
<MemoizedChild index={3} decrease={decrease} /> | |
<MemoizedChild index={4} decrease={decreaseCallback} /> | |
{UseMemoChild1} | |
{UseMemoChild2} | |
</main> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment