Bad news; There's not exactly a one-to-one comparison here. Functional components have access to useEffect, which can give us most of the functionality we got from methods like componentWillUpdate, componentDidUpdate, componentDidMount, componentWillUnmount, etc, but it's not quite the same.
The basics
If you want to make use of useEffect, you'll need to import it (it's a named export of React). useEffect takes a callback function and an optional array. This could be:
useEffect(() => console.log('You can define in line'))
Or
const someFunction = () => {
console.log('You can pass a function')
}
useEffect(someFunction)
These examples will call the effect every time the component renders or rerenders. This could be costly, if we don't want to call the effect every time, we need to pass a dependency array
Dependencies
If we only want to call the effect after the initial render, we can pass an empty dependency array to the hook.
useEffect(someFunction, [])
We can also have useEffect call the effect whenever certain things change by adding those values or references to the dependency array.
const [name, setName] = useState('')
useEffect(someFunction, [props.someValue, name])
In the above example, we will call the effect someFunction on initial render, as well as when the value of either props.someValue or name changes.
Cleanup
We might have effects that require cleanup, for example an asynchronous function or subscription. In this case, we need to make sure to include a cleanup function.
const [name, setName] = useState('')
useEffect(() => {
someFunctionThatWillNeedCleanup()
return someFunctionToDoCleanup()
}, [props.someValue, name])
For more information about effects and cleanup, visit the Effects with Cleanup section of the react docs.
Top comments (0)