DEV Community

JesseNReynolds
JesseNReynolds

Posted on

React Class vs Functional Components, Part 3: Lifecycle Methods

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'))
Enter fullscreen mode Exit fullscreen mode

Or

const someFunction = () => {
  console.log('You can pass a function')
}

useEffect(someFunction)
Enter fullscreen mode Exit fullscreen mode

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, [])
Enter fullscreen mode Exit fullscreen mode

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])
Enter fullscreen mode Exit fullscreen mode

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])
Enter fullscreen mode Exit fullscreen mode

For more information about effects and cleanup, visit the Effects with Cleanup section of the react docs.

Oldest comments (0)