Skip to content

Commit d05bde7

Browse files
committed
only setState when necessary
This avoids unnecessary app-rerenders by checking for relevant changes when new authentications happen.
1 parent fc2e430 commit d05bde7

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

src/provider.tsx

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,16 @@ export function AuthKitProvider(props: AuthKitProviderProps) {
3232
const onRefresh = React.useCallback(
3333
({ user, accessToken, organizationId }: AuthenticationResponse) => {
3434
const { role = null, permissions = [] } = getClaims(accessToken);
35-
setState((prev) => ({
36-
...prev,
37-
user,
38-
organizationId: organizationId ?? null,
39-
role,
40-
permissions,
41-
}));
35+
setState((prev) => {
36+
const next = {
37+
...prev,
38+
user,
39+
organizationId: organizationId ?? null,
40+
role,
41+
permissions,
42+
};
43+
return isEquivalentWorkOSSession(prev, next) ? prev : next;
44+
});
4245
},
4346
[client]
4447
);
@@ -79,6 +82,19 @@ export function AuthKitProvider(props: AuthKitProviderProps) {
7982
);
8083
}
8184

85+
// poor-man's "deep equality" check
86+
function isEquivalentWorkOSSession(
87+
a: typeof initialState,
88+
b: typeof initialState
89+
) {
90+
return (
91+
a.user?.updatedAt === b.user?.updatedAt &&
92+
a.organizationId === b.organizationId &&
93+
b.role === b.role &&
94+
a.permissions.every((perm, i) => perm === b.permissions[i])
95+
);
96+
}
97+
8298
const NOOP_CLIENT: Client = {
8399
signIn: async () => {},
84100
signUp: async () => {},

0 commit comments

Comments
 (0)