Skip to content

[ Small Optimization ] Excess useEffect dependency #15

@gclark-eightfold

Description

@gclark-eightfold

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions