react-native-appstate-hook icon indicating copy to clipboard operation
react-native-appstate-hook copied to clipboard

[ Small Optimization ] Excess useEffect dependency

Open gclark-eightfold opened this issue 4 years ago • 2 comments
trafficstars

Note: I could make a PR for this if this package is still being maintained and is open to PRs, but seeing as the directory structure only includes a dist folder, I assume this package only includes the JS-compiled package.

I was looking to wrap the RN AppState in my own custom hook and came across this package. While there's some functionality I still wish to add myself, I noticed that it looked like the hook has appState as a dependency, which creates a lot of excess listener creations and cleanups.

By modifying the handleAppStateChange function to:

function handleAppStateChange(nextAppState) {
  setAppState((prevAppState) => {
    if (nextAppState === 'active' && prevAppState !== 'active')
      isValidFunction(onForeground) && onForeground();
    else if (prevAppState === 'active' && nextAppState.match(/inactive|background/))
      isValidFunction(onBackground) && onBackground();
  });
  isValidFunction(onChange) && onChange(nextAppState);
}

and make the dependency list: [onChange, onForeground, onBackground] so that changes to the appState do not trigger the creation of a new AppState listener after the previous listener is cleaned up.

This change isn't strictly necessary, since the hook's appState and callback function calls remain unaffected by the number of times the change listeners are added/removed, but it was just something I noticed while testing the two methods.

gclark-eightfold avatar Oct 21 '21 19:10 gclark-eightfold

@gclark-eightfold forgot to return new appState in setAppState

laffed avatar Mar 03 '22 04:03 laffed

@laffed it should be like this:

    useEffect(() => {
        function handleAppStateChange(nextAppState) {
            setAppState((prevAppState) => {
                if (nextAppState === 'active' && prevAppState !== 'active') {
                    isValidFunction(onForeground) && onForeground();
                } else if (prevAppState === 'active' && nextAppState.match(/inactive|background/)) {
                    isValidFunction(onBackground) && onBackground();
                }

                return nextAppState;
            });
            isValidFunction(onChange) && onChange(nextAppState);
        }
    }, [onChange, onForeground, onBackground]);

alielmajdaoui avatar Jan 26 '23 16:01 alielmajdaoui