Skip to content

Commit

Permalink
Memoize context value in auth0-provider (#318)
Browse files Browse the repository at this point in the history
  • Loading branch information
claycoleman authored Jan 13, 2022
1 parent 1f46070 commit f8ee6c5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 15 deletions.
16 changes: 16 additions & 0 deletions __tests__/auth-provider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -813,4 +813,20 @@ describe('Auth0Provider', () => {
},
});
});

it('should not update context value after rerender with no state change', async () => {
clientMock.getTokenSilently.mockReturnThis();
clientMock.getUser.mockResolvedValue({ name: 'foo', updated_at: '1' });
const wrapper = createWrapper();
const { waitForNextUpdate, result, rerender } = renderHook(
() => useContext(Auth0Context),
{ wrapper }
);
await waitForNextUpdate();
const memoized = result.current;

rerender();

expect(result.current).toBe(memoized);
});
});
49 changes: 34 additions & 15 deletions src/auth0-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import React, { useCallback, useEffect, useReducer, useState } from 'react';
import React, {
useCallback,
useEffect,
useMemo,
useReducer,
useState,
} from 'react';
import {
Auth0Client,
Auth0ClientOptions,
Expand Down Expand Up @@ -364,21 +370,34 @@ const Auth0Provider = (opts: Auth0ProviderOptions): JSX.Element => {
[client]
);

const contextValue = useMemo(() => {
return {
...state,
buildAuthorizeUrl,
buildLogoutUrl,
getAccessTokenSilently,
getAccessTokenWithPopup,
getIdTokenClaims,
loginWithRedirect,
loginWithPopup,
logout,
handleRedirectCallback,
};
}, [
state,
buildAuthorizeUrl,
buildLogoutUrl,
getAccessTokenSilently,
getAccessTokenWithPopup,
getIdTokenClaims,
loginWithRedirect,
loginWithPopup,
logout,
handleRedirectCallback,
]);

return (
<Auth0Context.Provider
value={{
...state,
buildAuthorizeUrl,
buildLogoutUrl,
getAccessTokenSilently,
getAccessTokenWithPopup,
getIdTokenClaims,
loginWithRedirect,
loginWithPopup,
logout,
handleRedirectCallback,
}}
>
<Auth0Context.Provider value={contextValue}>
{children}
</Auth0Context.Provider>
);
Expand Down

0 comments on commit f8ee6c5

Please sign in to comment.