Last active
August 11, 2022 14:47
-
-
Save MichaelrMentele/c235537cd1608d255a6884d9e343348a to your computer and use it in GitHub Desktop.
Use effect basics
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
// 1. when will this useEffect render? | |
const SomeComponent = () => { | |
useEffect(() => { | |
console.log('useEffect') | |
}) | |
return null | |
} | |
// 2. how do you render a use effect once and not on re-renders? | |
// 3. does this useEffect re-render when onClick is called? why or why not? | |
const SomeComponent = () => { | |
const [formFields, setFormFields] = useState({ fooInput: 1, barInput: 2 }) | |
useEffect(() => { | |
console.log('useEffect') | |
}, [formFields]) | |
onClick = () => { | |
setFormFields({ fooInput: 1, barInput: 2}) | |
} | |
return <Button onClick={onClick} /> | |
} | |
// 4. does this useEffect re-render when onClick is called? why or why not? | |
const SomeComponent = () => { | |
const [formFields, setFormFields] = useState(false) | |
useEffect(() => { | |
console.log('useEffect') | |
}, [formFields]) | |
onClick = () => { | |
setFormFields(false) | |
} | |
return <Button onClick={onClick} /> | |
} | |
// 5. what is the bug here? what will happen on every button click? how do I fix this? | |
const SomeComponent = () => { | |
const [formFields, setFormFields] = useState(false) | |
useEffect(() => { | |
setTimeout(1000, () => { | |
console.log('timedout') | |
}) | |
}, [formFields]) | |
onClick = () => { | |
setFormFields(false) | |
} | |
return <Button onClick={onClick} /> | |
} | |
Answers below -- don't look until you've attempted this and engaged with the problems. | |
// Answers | |
1. every component render | |
2. pass it an empty list of dependencies | |
3. yes, because we instantiated a new object and so the state appears to have changed | |
4. no, because the value of state has not changed | |
5. the timeout isn't cleaned up and a new one is set on every re-render -- to fix return a clean up function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment