Optimizing useEffect in React

Hi, in this post we are going to see how to optimize the useEffect hook in React.

So, we have a parent component and child component

Note: look how the parent component is wrapping the child component

Now when the parent component suffer a render (because the count) then the child component is affected too and is being rendering also.

In this case we don’t need to run again and again the useEffect that is inside our child component

So, we can optimize the useEffect to avoid re-run again the useEffect callback and this could be possible by adding dependencies to our useEffect.

The dependencies are code that only the useEffect callback will be needed to be executed and those dependencies will be written inside an array after the callback like this: [name]

Nice! now if we run again the App then the useEffect code only will be executed one time (the first render).

And the useEffect code will be executed when the user write something in the input that’s it! (because the name is being updated

Here the entire code:

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

// CHILD Component
function Greeting({initialName = ''}) {
  console.log('Rendering child!!!')
  const [name, setName] = useState(
    () => window.localStorage.getItem('name') ?? initialName,
  )

  useEffect(() => {
    console.log('Enter into child useEffect!!!')
    window.localStorage.setItem('name', name)
  }, [name])

  function handleChange(event) {
    setName(event.target.value)
  }

  return (
    <div>
      <form>
        <label htmlFor="name">Name: </label>
        <input value={name} onChange={handleChange} id="name" />
      </form>
      {name ? <strong>Hello {name}</strong> : 'Please type your name'}
    </div>
  )
}

// PARENT component
function App() {
  const [count, setCount] = useState(0)
  console.log('Renderig Parent component!')

  return (
    <>
      <button onClick={() => setCount(previuosCount => previuosCount + 1)}>
        {count}
      </button>
      {/* CHILD component */}
      <Greeting />
    </>
  )
}

export default App

Note: You can use this plugin in your editor code

By Cristina Rojas.