Is it possible to cancel the subscription from a setCounter with a cleanup function in useEffect hook?

Asked
Active3 hr before
Viewed126 times

9 Answers

cleanupfunctioncanceluseeffectpossible
90%

Is it possible for everything that exists to have a definition? , Is it possible for user written algorithms to outperform libraries' built-in optimized functions? , Did all European countries choose to evacuate their diplomats from Afghanistan?

useEffect(() => {
   const timer = counter > 0 ? setTimeout(() => setCounter(counter - 1), 1000) : null
   return () => clearTimeout(timer)
}, [counter])
88%

Well, I found the problem of my code. It's because I mistakenly use useEffect, and I should use useLayoutEffect instead when I want to use requestAnimationFrame API.,The useEffect doesn't have subscriptions in itself. But, it calls startRaf() from useRaf which creates a subscription. However, it comes with a cleanup function!,Unlike componentDidMount or componentDidUpdate, effects scheduled with useEffect don’t block the browser from updating the screen. This makes your app feel more responsive. The majority of effects don’t need to happen synchronously. In the uncommon cases where they do (such as measuring the layout), there is a separate useLayoutEffect Hook with an API identical to useEffect.

export default function useRaf() {
   let [counter, setCounter] = useState(0);
   let rafID = useRef(null);

   function loop() {
      setCounter(counter => counter + 1);
      rafID.current = requestAnimationFrame(loop);
   }

   function start() {
      rafID.current = requestAnimationFrame(loop);
   }

   useEffect(() => {
      return () => {
         cancelAnimationFrame(rafID.current);
      };
   }, []);

   return [counter, start];
}
load more v
72%

The Effect Hook lets you perform side effects in function components:,Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. Whether or not you’re used to calling these operations “side effects” (or just “effects”), you’ve likely performed them in your components before.,We’ve learned that useEffect lets us express different kinds of side effects after a component renders. Some effects might require cleanup so they return a function:

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 (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
load more v
65%

Fixing DelayedIncreaser is simple: just return a cleanup function from the callback of useEffect():,Most likely you’ve read many posts on how to use React hooks. But knowing how Not to use, sometimes, is equally important as knowing how to use.,The best way to start with React hooks is to learn how to use them.

function FetchGame({ id }) {
  if (!id) {
    return 'Please select a game to fetch';
  }

  const [game, setGame] = useState({ 
    name: '',
    description: '' 
  });

  useEffect(() => {
    const fetchGame = async () => {
      const response = await fetch(`/api/game/${id}`);
      const fetchedGame = await response.json();
      setGame(fetchedGame);
    };
    fetchGame();
  }, [id]);

  return (
    <div>
      <div>Name: {game.name}</div>
      <div>Description: {game.description}</div>
    </div>
  );
}
load more v
75%

P.S. this lifecycle is also known as, the cleanup in a React hook function. ,React.useEffect is a basic hook that gets triggered on a combination of 3 React component lifecycles:,React useEffect is a function that gets executed for 3 different React component lifecycles.

Pretag
 Pretag team - issue, fix, solve, resolve
40%

Axios comes with a cancellation option to finish a request before it ends. This is useful besides the cleanup function to prevent memory leaking. ,There's a lot of other usages of the cleanup function on the useEffect hook, but I hope this can give you a better perspective of how and when to use it. Please add any comment or suggestion, I will appreciate. ,So, if we want to cleanup a subscription, the code would look like this:

Can 't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
load more v
22%

🤔 Do I need to specify functions as effect dependencies or not?,🤔 Question: Do I need to specify functions as effect dependencies or not?,It’s only after I stopped looking at the useEffect Hook through the prism of the familiar class lifecycle methods that everything came together for me.

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

  return (
    <div>
      <p>You clicked {count} times</p>      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
load more v
60%

Going through the docs, you will find mentions of a certain cleanup function. The cleanup function does exactly as it says – cleans up an effect. Where will it be required you might ask, well any cleanup function makes sense in cases where you have to unsubscribe from subscriptions or say remove Event Listeners.,You must be a little uncomfortable with this. How can cleanup function still see ‘old’ props once the next render has happened? Well, reiterating our learnings from above –,Here are some of the questions you might be having after employing the useEffect hook, which we’ll seek answers to 

Pretag
 Pretag team - issue, fix, solve, resolve
48%

A quick fix would be to return a cleanup function:,react-use - fix of the useRaf hook,Using the Effect Hook

function Counter() {
  const [counter, setCounter] = useState(0)

  useEffect(() => {
    document.title = `Counter: ${counter}`
  })

  return (
    <button onClick={() => setCounter(counter + 1)}>
      Clicked {counter} times
    </button>
  )
}
load more v

Other "cleanup-function" queries related to "Is it possible to cancel the subscription from a setCounter with a cleanup function in useEffect hook?"