DEV Community

Kadiri Talitu (Coded Salis)
Kadiri Talitu (Coded Salis)

Posted on • Originally published at Medium

Understanding React useEffect hook's Dependency

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

useEffect(setup, dependencies?)
Enter fullscreen mode Exit fullscreen mode

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(() => {
  //
}, [])
Enter fullscreen mode Exit fullscreen mode

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(() => {
  //
})
Enter fullscreen mode Exit fullscreen mode

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

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

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.

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Great article, you got my follow, keep writing!

Collapse
 
codedsalis profile image
Kadiri Talitu (Coded Salis)

Thanks man, I'm happy you liked it