Amplify UI

Advanced Usage

Access Authenticator UI component state outside of the UI component

useAuthenticator Hook

@aws-amplify/ui-react ships with useAuthenticator React hook that can be used to access, modify, and update Authenticator's auth state. To use them, you must render the Authenticator and wrap your application with <Authenticator.Provider>:

import { Authenticator } from '@aws-amplify/ui-react';

export default () => (
  <Authenticator.Provider>
    <App />
  </Authenticator.Provider>
);

Then, you can use useAuthenticator on your App:

import { useAuthenticator } from '@aws-amplify/ui-react';

const App = () => {
  const { user, signOut } = useAuthenticator((context) => [context.user]);
  // ...
};

Authenticator Provider

In advanced use cases where usage of the useAuthenticator hook outside the scope of the Authenticator is needed, wrap your application inside an Authenticator.Provider. The Authenticator.Provider guarantees that the useAuthenticator hook is available throughout your application.

import { Authenticator, View } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css'; // default theme

export default function App() {
  return (
    <Authenticator.Provider>
      <View>Your app here</View>
    </Authenticator.Provider>
  );
};
import { Authenticator } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css'; // default theme

export default function App(props) {
  return (
    <Authenticator.Provider>
      <View {...props}>Your app here</View>
    </Authenticator.Provider>
  );
};

Prevent Re-renders

Using useAuthenticator hook at your App level is risky, because it'll trigger a re-render down its tree whenever any of its context changes value.

To prevent undesired re-renders, you can pass a function to useAuthenticator that takes in Authenticator context and returns an array of desired context values. The hook will only trigger re-render if any of the array values change.

For example, you can ensure useAuthenticator to only reevaluate when its user context changes:

import { useAuthenticator } from '@aws-amplify/ui-react';

// hook below is only reevaluated when `user` changes
const { user, signOut } = useAuthenticator((context) => [context.user]);

Access Auth State

You can use useAuthenticator hook to access route string that represents the current authState. They can be one of:

  • idle
  • setup
  • signIn
  • signUp
  • confirmSignIn
  • confirmSignUp
  • setupTotp
  • forceNewPassword
  • forgotPassword
  • confirmResetPassword
  • verifyUser
  • confirmVerifyUser
  • signOut
  • authenticated
import { useAuthenticator } from '@aws-amplify/ui-react';
const App = () => {
const { route } = useAuthenticator(context => [context.route]);
// Use the value of route to decide which page to render
return route === 'authenticated' ? <Home /> : <Authenticator />;
};

Authentication Check

If you just need to check if you're authenticated or not, you can use the more straightforward useAuthenticator hook to access the authStatus string. The authStatus string can represent the following states:

  • configuring
  • authenticated
  • unauthenticated

The configuring state only occurs when the Authenticator is first loading.

import { useAuthenticator } from '@aws-amplify/ui-react';
const App = () => {
const { authStatus } = useAuthenticator(context => [context.authStatus]);
// Use the value of authStatus to decide which page to render
return (
<> {authStatus === 'configuring' && 'Loading...'} {authStatus !== 'authenticated' ? <Authenticator /> : <Home />} </> ); };

Access Authenticated User

You can use useAuthenticator hook to access current signed in user. If no user is authenticated, it'll return undefined.

import { useAuthenticator } from '@aws-amplify/ui-react';
const Home = () => {
const { user, signOut } = useAuthenticator((context) => [context.user]);
return ( <>
<h2>Welcome, {user.username}!</h2>
<button onClick={signOut}>Sign Out</button>
</> ); };

Trigger Transitions

You can use useAuthenticator hook to access functions that lets you trigger transitions to the authenticator. Please see Full API to see all supported transition functions. Any invalid transitions (e.g. signUp directly to authenticated) will be ignored.

import { useAuthenticator } from '@aws-amplify/ui-react';
const Home = () => {
const { user, signOut } = useAuthenticator((context) => [context.user]);
return <button onClick={signOut}>Welcome, {user.username}!</button>;
};

Example

Here's an example that uses the toForgotPassword trigger transition, to create a custom button. Note that example uses the Footer "slot" override.

import '@aws-amplify/ui-react/styles.css';
import {
  Authenticator,
  View,
  Button,
  useAuthenticator,
} from '@aws-amplify/ui-react';

export default function App() {
  const components = {
    SignIn: {
      Footer() {
        const { toForgotPassword } = useAuthenticator();
return (
<View textAlign="center"> <Button fontWeight="normal" onClick={toForgotPassword} size="small"> Forgot Password???
</Button>
</View> ); }, }, }; return ( <Authenticator components={components}> {({ signOut, user }) => ( <main> <h1>Hello {user.username}</h1> <button onClick={signOut}>Sign out</button> </main> )} </Authenticator> ); }

Full API

Below is the full list of context that useAuthenticator hook returns.

These are readonly contexts that represent the current auth state. Any unapplicable context will be undefined.

NameDescriptionType
userCurrent signed in userAuthUser
routeName of the auth flow user is instring
errorAny error returned from service API callstring
validationErrorsAny form validation errors found. Maps each error message to respective input name.Record<string, string>
hasValidationErrorsWhether there are any form validation errorsboolean
isPendingWhether service API call is in progressboolean
codeDeliveryDetailProvides detail on where confirm sign up code is sent to.CodeDeliveryDetail

These helper functions trigger transition to another route. Note that any invalid transition (e.g. sign-in to authenticated directly) will be no-op.

NameDescriptionType
toSignInTransitions to signIn. Allowed from signUp, confirmSignUp, confirmSignIn, setupTotp, forgotPassword, and confirmResetPassword() => void
toSignUpTransitions to signUp. Allowed from signIn.() => void
toForgotPasswordTransitions to forgotPassword. Allowed from signIn.() => void
skipVerificationSkips verification process. Allowed from verifyUser and confirmVerifyUser() => void

Amplify open source software, documentation and community are supported by Amazon Web Services.

© 2024 Amazon Web Services, Inc. and its affiliates. All rights reserved. View the site terms and privacy policy.

Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC.