Last active
June 25, 2022 18:26
-
-
Save rafinhaa/8fd36c1f6c3704215b5282139f44095e to your computer and use it in GitHub Desktop.
UseCallbackExample
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
// demo https://codesandbox.io/s/divine-sunset-tppu7o | |
import { useCallback, useEffect, useState } from "react"; | |
import "./styles.css"; | |
const Button = ({ onClick }: { onClick: () => void }) => { | |
useEffect(() => { | |
console.log("FILHO: mudou"); | |
}); | |
useEffect(() => { | |
console.log("FILHO: FUNÇÃO mudou"); | |
}, [onClick]); | |
return <button onClick={onClick}>Mudar</button>; | |
}; | |
export default function UseCallbackExample() { | |
const [count, setCount] = useState(0); | |
/** | |
* Quando algum estado muda efetua um Rerender no componente | |
* todas as funções e children são recriadas em memoria | |
* O useCallback mantém a referência da função, mesmo com tem rerender | |
*/ | |
const onClick = useCallback(() => { | |
setCount((oldState) => oldState + 1); | |
}, []); | |
useEffect(() => { | |
console.log("PAI: mudou"); | |
}); | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<h2>{count}</h2> | |
<Button onClick={onClick} /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment