简体   繁体   中英

How to avoid memory leaks with React Hooks

I have implemented a basic position transitioning animations using React JS, Material UI and framer-motion. And I have seen weird issues when the component is transitioning for a long time.

I have added cleanup method inside useEffect to avoid any possible leaks, but still I see the animations are laggy and the component is getting slow when I add it to actual codebase.

I tried my best following most of the blogs, but still didn't reach to the solution. Need some help here from this group.

This is what I tried:

Example

Instead of several useEffects in the same function, try using only one useEffect .

So in the exampe you gave, it would be something like this:

  useEffect(() => {
    const ref = container.current;
    if (container?.current?.style?.position === 'fixed') {
      setElementOffset(getSize(container.current));
    }
    let maxGrow: boolean;
    let backToNormal: boolean;
    paddingRange.onChange((rangeStatus) => {
      maxGrow = rangeStatus === '5%';
      backToNormal = rangeStatus === '0%';
      setIsComplete(maxGrow);
      setPosition(maxGrow ? 'static' : 'fixed');
      if (backToNormal) {
        setElementOffset(getSize(container.current));
      }
    });
    
    setElementOffset(getSize(ref));
    return () => {
      setIsComplete(maxGrow);
      setPosition(maxGrow ? 'static' : 'fixed');

      setElementOffset(getSize(ref));
    };
  }, [windowSize.width, elementOffset.offsetTop, paddingRange]);

Let me know if you have questions. The documentation for useEffect is https://reactjs.org/docs/hooks-effect.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM