Skip to content

Commit 054f373

Browse files
authored
Merge pull request #126 from brionmario/fix-strict-mode-issue
Add ref to handle strict mode re-renders in React 18
2 parents e443d0d + 86a7260 commit 054f373

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

lib/src/authenticate.tsx

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
import { SPACustomGrantConfig } from "@asgardeo/auth-spa/src/models/request-custom-grant";
3131
import React, {
3232
FunctionComponent,
33+
MutableRefObject,
3334
PropsWithChildren,
3435
ReactNode,
3536
createContext,
@@ -78,8 +79,6 @@ const AuthProvider: FunctionComponent<PropsWithChildren<AuthProviderPropsInterfa
7879
(): AuthReactConfig => ({ ...defaultConfig, ...passedConfig }), [ passedConfig ]
7980
);
8081

81-
const isSignInInitiated = useRef(false);
82-
8382
const signIn = async(
8483
config?: SignInConfig,
8584
authorizationCode?: string,
@@ -134,6 +133,7 @@ const AuthProvider: FunctionComponent<PropsWithChildren<AuthProviderPropsInterfa
134133
const trySignInSilently = () => AuthClient.trySignInSilently(state, dispatch);
135134

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

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

157-
isSignInInitiated.current = true;
162+
reRenderCheckRef.current = true;
158163

159164
(async () => {
160165
let isSignedOut: boolean = false;

0 commit comments

Comments
 (0)