Ryker
Ryker

Reputation: 577

Conditional re-render is re-rendering when setState is called with same value

Every time I call setState on isSignedIn even when the value doesn't change, it seems to be re-rendering and setting the screen back to the initial screen of the stack.

const {isAuthenticated, isVerified} = useAuth();
const [isSignedIn, setIsSignedIn] = useState(false);

useEffect(() => setIsSignedIn(isVerified && isAuthenticated), [isAuthenticated, isVerified]);

<NavigationContainer>
  <Root.Navigator initialRouteName={initialRouteName}>
    {!isSignedIn ? (
      <Root.Screen
        name="Auth"
        component={AuthStack}
        options={globalOptions}
      />
    ) : (
      <>
        <Root.Screen
          name="Tab"
          component={TabStack}
          options={globalOptions}
        />
      </>
    )}
  </Root.Navigator>
</NavigationContainer>

Upvotes: 1

Views: 998

Answers (2)

Ryker
Ryker

Reputation: 577

Figured it out. I had a problem with the way I was setting isVerified that it would be set to true for a moment then false.

Problem code in my auth provider:

function updateIsVerified(user) {
    if (attemptedLoginMethod === 'facebook') {
      setIsVerified(true);
    } else {
      setIsVerified(user?.emailVerified ?? false);
    }

The attemptedLoginMethod was not being set to the correct method before updateIsVerified is called.

Upvotes: 1

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

This might help

useEffect(() => {
  if( isVerified && isAuthenticated ){
    setIsSignedIn(true);
  }
 }, [isAuthenticated, isVerified]
);

Upvotes: 0

Related Questions