DEV Community

Helder Burato Berto
Helder Burato Berto

Posted on • Originally published at helderberto.com

Effects with React useEffect

Some practical examples of how to use the React useEffect() -

import React from "react";

export default function App() {
  const [name, setName] = React.useState('');
  const [age, setAge] = React.useState(0);

  React.useEffect(() => {
    console.log('component mounted');

    return () => {
      console.log('component unmounted');
    }
  }, []); // empty array means it will only run on mounting

  // Separation of concerns
  // This is a good example of how to separate concerns splitting into two useEffects to handle each value
  React.useEffect(() => {
    console.log('name changed', name);
  }, [name]); // only triggers when name changes

  React.useEffect(() => {
    console.log('age changed', age);
  }, [age]); // only triggers when age changes

  return (
    <div>
      <input type="text" value={name} onChange={e => setName(e.target.value)} />
      <input type="number" value={age} onChange={e => setAge(e.target.value)} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

On Mounting

Similar to the legacy componentDidMount it will trigger on mounting the component:

React.useEffect(() => {
  console.log('component mounted');

  return () => {
    console.log('component unmounted');
  }
}, []); // empty array means it will only run on mounting
Enter fullscreen mode Exit fullscreen mode

On Changing Values

React.useEffect(() => {
  console.log('name changed', name);
}, [name]); // only triggers when name changes
Enter fullscreen mode Exit fullscreen mode

Separation of Concerns

Instead of watching two values at the same useEffect, like the following:

React.useEffect(() => {
  console.log({ name, age });
}, [name, age]);
Enter fullscreen mode Exit fullscreen mode

Think in separation of concerns, and split each it will be cleaner and easier for the next person who need to read your code, eg:

// Separation of concerns
// This is a good example of how to separate concerns splitting into two useEffects to handle each value
React.useEffect(() => {
  console.log('name changed', name);
}, [name]); // only triggers when name changes

React.useEffect(() => {
  console.log('age changed', age);
}, [age]); // only triggers when age changes
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
nzawirski profile image
Nikodem Zawirski

I think there is a mistake in the last code block. I think the second useEffect should have had age in its dependency array

Collapse
 
helderberto profile image
Helder Burato Berto

Thanks! Fixed.