0

I have a function that is supposed to set a piece of state to true if a condition is truthy and show appropriate UI.

This sort of works but then it throws a no-op error and flicks back to false immediately. I am also using a use effect to check on first render if the condition is truthy and show appropriate UI if so.

I am trying to use a teardown but am not familiar with them really. Any advice or pointers?

Error:

Warning: 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.

Functions

  const [isPatched, setIsPatched] = useState<boolean>(false);

  useEffect(() => {
    getApplied(x);
    return () => {
      setIsPatched(false);
    };
  }, []);

  const getApplied = (x: any) => {
    console.log(x);
    if (x.Log) {
      setIsPatched(true);
      return;
    } else {
      setIsPatched(false);
    }
  };
deadant88
  • 920
  • 9
  • 24
  • 2
    The callback in the `useEffect` will run when unmounting. You can not set state when unmounting – RubenSmn Jan 31 '23 at 08:52
  • Any advice on how to prevent that? – deadant88 Jan 31 '23 at 08:55
  • 1
    Don't set state in the return of a useEffect if there are no dependencies in the dependency array. For some more info you can checkout this [SO post](https://stackoverflow.com/questions/71258604/how-to-fix-react-warning-cant-perform-a-react-state-update-on-an-unmounted-co) – RubenSmn Jan 31 '23 at 08:57
  • I thought that was how you unmount – deadant88 Jan 31 '23 at 08:59
  • That post, while interesting, is related to Fetch and Axios - I'm not using those - just a useEffect. The API hits a database – deadant88 Jan 31 '23 at 09:03
  • Please show the full component – Konrad Jan 31 '23 at 09:21
  • 1
    The point is that you use the return function of the useEffect to ***cleanup***, e.g. remove event listeners, abort calls to a api. But when you setState in the cleanup function it will throw the warning you mentioned since when unmounted there is no state anymore to set. Once your component will be mounted again the **initialstate** will be `false` so there is no need to ***reset*** the state if that's what you're thinking – RubenSmn Jan 31 '23 at 09:22

0 Answers0