DEV Community

csdj92
csdj92

Posted on

useEffect Hook

Getting Started

The main function of the useEffect hook is to allow you to perform side effects in functional components. Fetching data, changing the DOM and setting up a subscription are all examples of side effects.
If you have worked with react before you should have came across componentDidMount and componentDidUpdate you can think of useEffect and a combination of them both.

Not a true lifecycle

useEffect runs after every render by default both after the first render and after after every update. While thinking useEffect does the job of three separate lifecycles, it is better to think of it as a way to run side effects after render.

Here are some examples from the docs "In a React class, you would typically set up a subscription in componentDidMount, and clean it up in componentWillUnmount. For example, let’s say we have a ChatAPI module that lets us subscribe to a friend’s online status. Here’s how we might subscribe and display that status using a class:

 class FriendStatus extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isOnline: null };
    this.handleStatusChange = this.handleStatusChange.bind(this);
  }

  componentDidMount() {
    ChatAPI.subscribeToFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }
  componentWillUnmount() {
    ChatAPI.unsubscribeFromFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }
  handleStatusChange(status) {
    this.setState({
      isOnline: status.isOnline
    });
  }

  render() {
    if (this.state.isOnline === null) {
      return 'Loading...';
    }
    return this.state.isOnline ? 'Online' : 'Offline';
  }
}; 


Enter fullscreen mode Exit fullscreen mode

With Hooks:

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

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}; 


Enter fullscreen mode Exit fullscreen mode

Top comments (0)