rsm-hcd / AndcultureCode.JavaScript.React

Common patterns, functions, etc... used when building react applications
6 stars 8 forks source link

Optimization in use-page-errors resetPageErrors function #54

Open brandongregoryscott opened 3 years ago

brandongregoryscott commented 3 years ago

In a recent debugging session on a client project, we found that some unnecessary state changes were being kicked off by the use-page-errors hook, specifically the resetPageErrors function that is exported. Add a simple check with the callback version of setPageErrors to check to see if the previous state has values - if it doesn't, there's no need to set the state and cause a re-render to consuming components (due to referential inequality of arrays).

Before:

const resetPageErrors = useCallback(() => {
    setPageErrors([]);
}, []);

After:

const resetPageErrors = useCallback(() => {
    setPageErrors((prevState) =>
        CollectionUtils.hasValues(prevState) ? [] : prevState
    );
}, []);