React JS useEffect hook

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

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    

You clicked {count} times

); }
  • Similar to useState, you can call useEffect multiple times for multiple different purposes.
  • The code inside the useEffect block is being called after the the component is rendered.
  • By default, it runs both after the first render and after every update.

  • 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';
    }
    
  • Every effect may return a function that cleans up after it. This lets us keep the logic for adding and removing subscriptions close to each other. In this example, it unsubscribes when the component unmounts.
  • React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.

  • useEffect(() => {
      document.title = `You clicked ${count} times`;
    }, [count]); // Only re-run the effect if count changes
    

    By passing in a second argument to the useEffect call, with an array of variables makes the effect to be ran only when those variable changes. In this example, the effect will only re-run if count changes.

    Reference: https://reactjs.org/docs/hooks-effect.html

    Search within Codexpedia

    Custom Search

    Search the entire web

    Custom Search