React useEffect()

React Rendering

  • React is really smart
  • It only updates what needs to be updated
  • Reconciliation

Reconciliation

What are Hooks?

  • React used to be class Component based
  • React is now built using functional Components
  • Hooks are how we manage state and react to state

Lifecycle Methods

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

Now With Hooks...

const Clock = (props) => {
  const [date, setDate] = useState(new Date());
  
  useEffect(() => {
    const tick = () => {
      setDate(new Date());
    };
  
    const timerID = setInterval(tick, 1000);
    
    return () => clearInterval(timerID);
  }, [])
  
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {date.toLocaleTimeString()}.</h2>
    </div>
  );
};

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

What's different?

  • Instead of creating an instance of the class and calling methods...
  • We're calling the component function every time

A problem...

  • Equating lifecylce methods and hooks
  • Kind of works, but shouldn't
  • Usually involves useEffect (kind of the "catch all" hook)

Common useEffect Pitfalls

  • Not using (or ignoring) the ESLint plugin
  • Thinking in Lifecycles
  • And some more, that I don't feel are really that important

ESLint

  • exhaustive-deps rule
  • Actually super duper important
  • 'Just trust me, every time I thought "oh, I don't need to follow the rule this time" I later regretted disabling it because I was wrong.' -- Kent Dodds
  • ^^ Me too

Thinking in Lifecycles

  • useEffect(() => {}, []) ≠ componentDidMount() {}
  • You have to think about effects in a different way

Same "exhaustive-deps" thing

'So when you're thinking: "Hey, my dependencies list needs to be []" don't do that because you think it only needs to run on mount, do it because you know that the stuff it's doing will never get stale.'
-- Kent Dodds

Fetching with useEffect

Custom hooks

  • Along with useReducer, useEffect is the backbone
  • useReducer is awesome
  • useEffect is awesome
  • Hooks are just awesome in general and are really cleverly written

The End

React useEffect()

By Ethan Brouwer

React useEffect()

  • 281