Skip to content

Commit

Permalink
Merge pull request #126 from brionmario/fix-strict-mode-issue
Browse files Browse the repository at this point in the history
Add ref to handle strict mode re-renders in React 18
  • Loading branch information
brionmario committed Aug 22, 2022
2 parents e443d0d + 86a7260 commit 054f373
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions lib/src/authenticate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
import { SPACustomGrantConfig } from "@asgardeo/auth-spa/src/models/request-custom-grant";
import React, {
FunctionComponent,
MutableRefObject,
PropsWithChildren,
ReactNode,
createContext,
Expand Down Expand Up @@ -78,8 +79,6 @@ const AuthProvider: FunctionComponent<PropsWithChildren<AuthProviderPropsInterfa
(): AuthReactConfig => ({ ...defaultConfig, ...passedConfig }), [ passedConfig ]
);

const isSignInInitiated = useRef(false);

const signIn = async(
config?: SignInConfig,
authorizationCode?: string,
Expand Down Expand Up @@ -134,6 +133,7 @@ const AuthProvider: FunctionComponent<PropsWithChildren<AuthProviderPropsInterfa
const trySignInSilently = () => AuthClient.trySignInSilently(state, dispatch);

const [ error, setError ] = useState<AsgardeoAuthException>();
const reRenderCheckRef: MutableRefObject<boolean> = useRef(false);

useEffect(() => {
if (state.isAuthenticated) {
Expand All @@ -149,12 +149,17 @@ const AuthProvider: FunctionComponent<PropsWithChildren<AuthProviderPropsInterfa
* Try signing in when the component is mounted.
*/
useEffect(() => {
// Prevent multiple renderings
if (isSignInInitiated.current) {
// React 18.x Strict.Mode has a new check for `Ensuring reusable state` to facilitate an upcoming react feature.
// https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state
// This will remount all the useEffects to ensure that there are no unexpected side effects.
// When react remounts the signIn hook of the AuthProvider, it will cause a race condition. Hence, we have to
// prevent the re-render of this hook as suggested in the following discussion.
// https://github.com/reactwg/react-18/discussions/18#discussioncomment-795623
if (reRenderCheckRef.current) {
return;
}

isSignInInitiated.current = true;
reRenderCheckRef.current = true;

(async () => {
let isSignedOut: boolean = false;
Expand Down

0 comments on commit 054f373

Please sign in to comment.