Lesson 57 of 60 – Login and Registration in React Native
95%

Login and Registration in React Native

Login and registration are common features in mobile applications. Registration allows a new user to create an account, while login allows an existing user to access that account.

In a React Native application, the user interface is created using React Native components such as TextInput, Button, Pressable, and ActivityIndicator. The actual account creation and credential verification are normally performed by a backend API.

Note: A production authentication system should validate credentials on the server and use HTTPS for communication. Client-side validation improves the user experience but does not replace server-side validation.

1. What is User Registration?

Registration is the process of creating a new user account.

A registration form may ask for information such as:

  • Name
  • Email address
  • Password
  • Mobile number
Registration Form
       ↓
User Details
       ↓
Backend API
       ↓
Create Account
       ↓
Registration Success

2. What is User Login?

Login is the process through which an existing user provides credentials to access an account.

Email + Password
       ↓
Backend API
       ↓
Verify Credentials
       ↓
Success / Failure

3. Registration and Login Flow

New User
   ↓
Registration
   ↓
Account Created
   ↓
Login
   ↓
Authentication
   ↓
Application Home

Existing User
   ↓
Login
   ↓
Authentication
   ↓
Application Home

4. Creating a Registration Screen

A registration screen can contain several input fields.

<TextInput
    placeholder="Name"
/>

<TextInput
    placeholder="Email"
/>

<TextInput
    placeholder="Password"
    secureTextEntry
/>

<Button
    title="Register"
    onPress={handleRegister}
/>

5. Managing Registration State

React state can store the values entered into registration fields.

const [name, setName] =
    useState("");

const [email, setEmail] =
    useState("");

const [password, setPassword] =
    useState("");

Each TextInput can update its corresponding state value.

6. Registration TextInputs

<TextInput
    placeholder="Full Name"
    value={name}
    onChangeText={setName}
/>

<TextInput
    placeholder="Email"
    value={email}
    onChangeText={setEmail}
/>

<TextInput
    placeholder="Password"
    value={password}
    onChangeText={setPassword}
    secureTextEntry
/>

7. Validating Registration Fields

Before sending registration data to the server, the application can perform basic validation.

if (!name || !email || !password) {

    setError(
        "Please fill all fields"
    );

    return;

}

The backend should perform its own validation as well.

8. Basic Email Validation

A simple regular expression can be used for basic client-side email format checking.

const emailPattern =
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (!emailPattern.test(email)) {

    setError(
        "Enter a valid email address"
    );

    return;

}

This checks the format only. The server should still validate the email.

9. Password Validation

A registration form can check basic password requirements before sending the request.

if (password.length < 6) {

    setError(
        "Password must contain at least 6 characters"
    );

    return;

}

The exact password policy should be defined by the application's backend and security requirements.

10. Sending Registration Data to an API

After validation, registration data can be sent to a backend API using fetch().

const response = await fetch(
    "https://example.com/api/register",
    {
        method: "POST",

        headers: {
            "Content-Type":
                "application/json"
        },

        body: JSON.stringify({
            name,
            email,
            password
        })
    }
);

11. Handling Registration Response

const data =
    await response.json();

if (response.ok) {

    console.log(
        "Registration successful"
    );

} else {

    console.log(
        data.message
    );

}

The backend determines the response format and status codes.

12. Displaying Registration Errors

An error state can be used to display a registration error to the user.

const [error, setError] =
    useState("");

...

{error
    ? <Text>{error}</Text>
    : null
}

For example, the server may report that an email address is already registered.

13. Handling Successful Registration

After successful registration, the application can navigate the user to the login screen or continue into an appropriate authenticated flow, depending on the application's design.

if (response.ok) {

    navigation.navigate(
        "Login"
    );

}

14. Creating a Login Screen

A basic login screen normally requires an email and password.

const [email, setEmail] =
    useState("");

const [password, setPassword] =
    useState("");

const [error, setError] =
    useState("");
<TextInput
    placeholder="Email"
    value={email}
    onChangeText={setEmail}
/>

<TextInput
    placeholder="Password"
    value={password}
    onChangeText={setPassword}
    secureTextEntry
/>

15. Handling Login

The login function sends the user's credentials to the backend.

async function handleLogin() {

    if (!email || !password) {

        setError(
            "Enter email and password"
        );

        return;

    }

    // Send request to API

}

16. Login API Request

const response = await fetch(
    "https://example.com/api/login",
    {
        method: "POST",

        headers: {
            "Content-Type":
                "application/json"
        },

        body: JSON.stringify({
            email,
            password
        })
    }
);

The server receives the credentials and performs the authentication check.

17. Handling Successful Login

When login succeeds, the application can update its authentication state and move the user into the authenticated part of the application.

if (response.ok) {

    const data =
        await response.json();

    onLogin(data);

}

18. Handling Invalid Login

if (!response.ok) {

    const data =
        await response.json();

    setError(
        data.message ||
        "Invalid login details"
    );

    return;

}

The server should return an appropriate response when authentication fails.

19. Adding a Loading State

Registration and login requests can take some time. A loading state can prevent repeated submissions and provide feedback.

const [loading, setLoading] =
    useState(false);
setLoading(true);

try {

    // API request

} finally {

    setLoading(false);

}

20. Showing ActivityIndicator

{loading ? (

    <ActivityIndicator />

) : (

    <Button
        title="Login"
        onPress={handleLogin}
    />

)}

This gives the user visual feedback while the authentication request is being processed.

21. Password Confirmation

A registration form may ask the user to enter the password twice.

const [confirmPassword,
    setConfirmPassword] =
    useState("");

if (password !== confirmPassword) {

    setError(
        "Passwords do not match"
    );

    return;

}

This provides an additional client-side check before the registration request.

22. Login and Registration Navigation

React Navigation can be used to move between authentication screens.

Login
  ↓
Register

Register
  ↓
Login

Login
  ↓
Home

For example:

navigation.navigate(
    "Register"
);

23. Authentication State After Login

The application can maintain a central authentication state.

const [user, setUser] =
    useState(null);

After successful login:

setUser(data.user);

When the user logs out:

setUser(null);

24. Login and Registration with AsyncStorage

An application may use appropriate local storage to remember non-sensitive session information or identifiers.

await AsyncStorage.setItem(
    "userId",
    String(data.user.id)
);

The application can read the stored information when it starts and then perform the required session validation.

Important: Do not store passwords in AsyncStorage. Sensitive authentication credentials require an appropriate secure storage mechanism.

25. Login and Registration with Axios

Axios can also be used for registration and login requests.

const response = await axios.post(
    "https://example.com/api/register",
    {
        name,
        email,
        password
    }
);

console.log(response.data);

A login request can use the same approach with the appropriate API endpoint.

26. Common Login and Registration Mistakes

  • Not validating required fields.
  • Relying only on client-side validation.
  • Sending authentication requests without HTTPS in production.
  • Storing passwords in AsyncStorage.
  • Ignoring server error responses.
  • Allowing repeated submissions while a request is running.
  • Not handling network errors.
  • Not checking password confirmation during registration.
  • Hard-coding sensitive credentials in the application.
  • Not clearing authentication state during logout.

27. Complete Registration Example

async function handleRegister() {

    setError("");

    if (!name || !email || !password) {

        setError(
            "Please fill all fields"
        );

        return;

    }

    if (password !== confirmPassword) {

        setError(
            "Passwords do not match"
        );

        return;

    }

    setLoading(true);

    try {

        const response = await fetch(
            "https://example.com/api/register",
            {
                method: "POST",

                headers: {
                    "Content-Type":
                        "application/json"
                },

                body: JSON.stringify({
                    name,
                    email,
                    password
                })
            }
        );

        const data =
            await response.json();

        if (!response.ok) {

            setError(
                data.message ||
                "Registration failed"
            );

            return;

        }

        navigation.navigate(
            "Login"
        );

    } catch (error) {

        setError(
            "Network error"
        );

    } finally {

        setLoading(false);

    }

}

28. Login and Registration Best Practices

  • Use HTTPS for production API requests.
  • Validate form fields on the client and server.
  • Never store passwords locally.
  • Use secure authentication mechanisms for sensitive credentials.
  • Show loading feedback during API requests.
  • Display useful authentication errors.
  • Prevent duplicate form submissions.
  • Keep authentication state centralized.
  • Handle logout and session expiration properly.
  • Keep registration and login screens simple and user-friendly.

29. Important Login and Registration Concepts

Concept Purpose
Registration Creates a new user account
Login Authenticates an existing user
Validation Checks whether submitted data meets requirements
Loading State Shows that an authentication request is in progress
Authentication State Represents the current authentication status
Logout Ends the user's application session
Protected Screen Screen intended for authenticated users

30. Complete Login and Registration Workflow

New User
   ↓
Registration Screen
   ↓
Enter User Details
   ↓
Validate Form
   ↓
Registration API
   ↓
Account Created
   ↓
Login Screen
   ↓
Enter Credentials
   ↓
Login API
   ↓
Verify Credentials
   ↓
Authentication Success
   ↓
Update Authentication State
   ↓
Protected Application
   ↓
Logout
   ↓
Authentication State Cleared

Login and registration form the foundation of account-based mobile applications. React Native provides the components and application logic for these screens, while the backend normally handles account creation, credential verification, and authentication sessions.

📌 Key Points

  • Registration creates a new user account.
  • Login authenticates an existing user.
  • React Native can build the login and registration interfaces.
  • Backend APIs should perform actual credential verification.
  • Validate form data before sending requests.
  • The server must also validate all authentication data.
  • Use loading states during API requests.
  • Handle successful and failed authentication responses.
  • Use navigation to move between login, registration, and application screens.
  • Do not store passwords in AsyncStorage.
  • Use HTTPS for production authentication communication.
  • Keep authentication state organized and centralized.

🧠 Quick Quiz

Question: What is the main purpose of a registration screen?