Understanding React useEffect hook's Dependency

Understanding React useEffect hook's Dependency

The useEffect hook in react can be quite confusing especially when you're still new to the library and trying to understand the bits that hold it together. According to the React documentation, useEffect is a React Hook that lets you synchronize a component with an external system and its syntax is:

useEffect(setup, dependencies?)

setup is a callback function where you define your logic and dependencies? is an optional array of variables you can pass to the effect that determines how often the code in the setup callback function will be executed. Here are some behaviours of the useEffect hook given the different scenarios

1. Empty dependencies array

useEffect(() => {
  //
}, [])

Leaving the dependency arrays empty as shown in the example above will make sure that the code in the setup callback function will be executed only once, that is when the component is mounted.

2. No dependencies array passed

useEffect(() => {
  //
})

When you do not pass any dependency array to the useEffect hook as in the example above, the code in the setup callback function will be executed every time the component renders or after every re-render

3. Passing a variable name to the dependency

useEffect(() => {
  //
}, [var1, var2]);

Passing a variable name or list of variable names eg: var1, var2, etc inside the array means that the code in the setup callback function will be executed every time the state of that variable changes. For example, in the code below, the code in the setup callback function will be executed each time the counter is incremented

import React, { useEffect, useState } from 'react'

export function App() {
  const [counter, setCounter] = useState(0)

  useEffect(() => {
    console.log('effect code executed')
  }, [counter])

  return (
    <div>
      <p>Counter: { counter }</p>
      <button onClick={()=> setCounter(counter+1)}>
        Increment me!
      </button>
    </div>
  )
}

Thank you for taking the time to read through it. I hope you enjoyed learning as much as I enjoyed preparing it and if you have any thoughts or comments, please feel free to share them in the comments section.