npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-redux-django-auth

v1.4.5

Published

A React Redux Authentication system for django app built with TypeScript.

Readme

React-Redux Authentication Hooks

This package provides a suite of custom React hooks and a Redux Provider to streamline authentication in your application. By integrating with Redux, it offers a predictable state management solution for handling user authentication status, data, and errors.

Installation

To get started, you'll need to install the package and its dependencies.

npm install react-redux-django-auth react-redux redux axios

or using yarn

yarn add react-redux-django-auth react-redux redux axios

How to Use

The core of this package is the AuthProvider component. This component wraps your entire application, making the Redux store available to all child components. This is a crucial step for the authentication hooks to function correctly.

Wrap Your Application

The first step is to wrap your main App component with the AuthProvider. This is typically done in your entry file, such as index.tsx or index.js.

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import {AuthProvider} from 'react-redux-django-auth'; // Add this import line

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);

root.render(
<React.StrictMode>
    <BrowserRouter>
        <AuthProvider>
            <App />
        </AuthProvider>
    </BrowserRouter>
</React.StrictMode>
);

By doing this, any component within your application can now access the authentication state and dispatch actions using the custom hooks provided by this package.

Using the Hooks

Once the AuthProvider is in place, you can use any of the custom hooks (like useFacebookAuth, useGoogleAuth, etc.) in your components. These hooks handle the logic for authentication, state management, and error handling, making your components cleaner and easier to maintain. For example, a login component might use the useFacebookAuth hook to initiate the login process.

Login Hook Usage

The useLogin hook is a custom hook designed to manage the state and logic for a login form, integrating directly with your Redux store for authentication. It handles form data, loading states, and dispatches login actions.

  1. Import the Hook and Set Up Initial State

    First, import the useLogin hook into your component. You'll need to define an object for your initial form state, which should match the expected fields for your login form (e.g., email, password), as required in your django backend.

    import {useLogin} from "react-redux-django-auth";
    
    const initialFormData = {
        email: "",
        password: "",
    };
  2. Call the Hook in Your Component

    Call the useLogin hook inside your functional component, passing the initialFormData and your API URL as arguments. The hook will return an object containing everything you need to manage your login form.

    const apiURL = process.env.REACT_APP_API_URL; //Setup REACT_APP_API_URL in .env
    
    const LogIn = () => {
    const initialFormData = {
        email: "",
        password: "",
    };
    
    const { error, formData, isStatus200, loading, onChange, onSubmit } =
        useLogin(initialFormData, apiURL);
    
    // ... rest of your component logic
    };
  3. Connect the Returned Values to Your Form

    Now, use the values returned from the hook to manage your form's state and behavior.

    • formData: Binds the input values to the form state.

    • onChange: Updates the form state as the user types.

    • onSubmit: Handles the form submission, dispatches the login action, and manages the loading state.

    • loading: A boolean value to disable the submit button during a network request.

    • error: Displays any authentication errors returned from the Redux state.

    • isStatus200: If the status is 200, perform actions like navigation to a new page

    <form className="row g-3" onSubmit={(e) => onSubmit(e)}>
      {/* Email Input */}
      <input
        type="email"
        name="email"
        onChange={(e) => onChange(e)}
        value={formData.email}
        required
      />
    
      {/* Password Input */}
      <input
        type="password"
        name="password"
        onChange={(e) => onChange(e)}
        value={formData.password}
        required
      />
    
      {/* Submit Button */}
      <button type="submit" disabled={loading}>
        {loading ? "Logging In..." : "Log In"}
      </button>
    
      {/* Display Error Message */}
      {error && <div className="text-danger">{error}</div>}
    </form>

Signup Hook Usage

The useSignup hook is a custom hook designed to manage the state and logic for a user registration form. It integrates with your Redux store to handle form data, loading states, and dispatches sign-up actions.

  1. Import the Hook and Set Up Initial State

    First, import the useSignup hook into your component. You'll need to define an object for your initial form state, which should match the expected fields for your sign-up form (e.g., email, password, etc.).

    import {useSignup} from "react-redux-django-auth";
    
    const initialFormData = {
         // Add other fields as needed
     email: "",
     password: "",
     re_password: "",
    };
  2. Call the Hook in Your Component Call the useSignup hook inside your functional component, passing the initialFormData and your API URL as arguments. The hook will return an object containing everything you need to manage your sign-up form.

    const apiURL = process.env.REACT_APP_API_URL;
    
    const Signup = () => {
     const initialFormData = {
         // Add other fields as needed
         email: "",
         password: "",
         re_password: "",
     };
    
     const { error, formData, isStatus201, loading, onChange, onSubmit } =
     useSignup(initialFormData, apiURL);
    
     // ... rest of your component logic
    };
  3. Connect the Returned Values to Your Form

    Use the values returned from the hook to manage your form's state and behavior.

    • formData: Binds the input values to the form state.

    • onChange: Updates the form state as the user types.

    • onSubmit: Handles the form submission, dispatches the sign-up action, and manages the loading state.

    • loading: A boolean value to disable the submit button during a network request.

    • error: Displays any authentication errors returned from the Redux state.

    <form className="row g-3" onSubmit={(e) => onSubmit(e)}>
      {/* Email Input */}
      <input
        type="email"
        name="email"
        onChange={(e) => onChange(e)}
        value={formData.email}
        required
      />
      // Add other form data
      {/* Submit Button */}
      <button type="submit" disabled={loading}>
        {loading ? "Signing Up..." : "Sign Up"}
      </button>
      {/* Display Error Message */}
      {error && <div className="text-danger">{error}</div>}
    </form>

useActivate Hook Usage

The useActivate hook is a custom hook designed to handle the user account activation process. It leverages Redux to dispatch the necessary verify action, manages the loading state during the API call, and provides feedback on the activation status and any errors.

1. Import the Hook and Get Parameters

First, import the useActivate hook into your component. Typically, account activation links contain uid and token parameters, which you can extract from the URL using useParams from react-router-dom.

import { useActivate } from "react-redux-django-auth";
import { useParams } from "react-router-dom";

const ActivateAccount = () => {
  const { uid, token } = useParams();
  const apiURL = process.env.REACT_APP_API_URL;
  // ...
};

2. Call the Hook in Your Component

Call the useActivate hook inside your functional component, passing the uid, token, and your API URL as arguments. The hook will return an object with the logic needed to manage the activation.

const { error, loading, onSubmit, isStatus204 } = useActivate(
  uid,
  token,
  apiURL
);

3. Connect the Returned Values to Your UI

Use the values returned from the hook to manage your component's state and behavior.

  • onSubmit: This function triggers the account activation process. You should connect it to a button's onClick event.
  • loading: A boolean value to disable the button and show a loading spinner while the API call is in progress.
  • error: Displays any activation errors returned from the Redux state.
  • isStatus204: A boolean that can be used to detect a successful activation (a 204 No Content status is often used for successful, non-returning operations).
<form onSubmit={onSubmit}>
  {/* The button that triggers the activation */}
  <button
    type="submit"
    onClick={onSubmit}
    disabled={loading}
    className={loading ? "btn btn-primary disabled" : "btn btn-primary"}
  >
    {loading && <LoaderIcon />}
    Click here to Verify your Account
  </button>

  {/* Display Error Message */}
  {error && <div className="text-danger">{error}</div>}
</form>

useResetPassword Hook

The useResetPassword hook is designed to manage the state and logic for a password reset request. It provides a simple way to handle the email input, loading state, and the form submission process, dispatching a Redux action to request the password reset.

1. Call the Hook in Your Component

Call the useResetPassword hook inside your functional component, passing your API URL as an argument. The hook will return an object with all the necessary state and functions to build a password reset form.

import { useResetPassword } from "react-redux-django-auth";

const ResetPasswordPage = () => {
  const apiURL = process.env.REACT_APP_API_URL;
  const { email, loading, handleChange, error, handleSubmit, isStatus204 } =
    useResetPassword(apiURL);

  // ... rest of your component logic
};

2. Connect the Returned Values to Your Form

Use the values returned from the hook to manage your form's state and behavior.

  • email: Binds the input value to the form state.
  • handleChange: Updates the form state as the user types. This function is specifically for a single email input field.
  • handleSubmit: Handles the form submission, dispatches the password reset action, and manages the loading state.
  • loading: A boolean value to disable the submit button during the API request.
  • error: Displays any authentication errors returned from the Redux state.
  • isStatus204: A boolean value that becomes true upon a successful submission, useful for showing success messages or redirecting the user.
<form onSubmit={handleSubmit}>
  {/* Email Input */}
  <input
    type="email"
    name="email"
    onChange={handleChange}
    value={email}
    required
  />

  {/* Submit Button */}
  <button type="submit" disabled={loading}>
    {loading ? "Sending..." : "Reset Password"}
  </button>

  {/* Display Error Message */}
  {error && <div className="text-danger">{error}</div>}

  {/* Success Message (optional) */}
  {isStatus204 && (
    <div className="text-success">Password reset email sent!</div>
  )}
</form>

usePasswordConfirm Hook

The usePasswordConfirm hook is designed to manage the state and logic for confirming a new password after a reset request. This hook handles the form data for the new password fields, manages the loading state, and dispatches the necessary Redux action to finalize the password change.

1. Import the Hook and Set Up Initial State

First, import the usePasswordConfirm hook into your component. The hook requires an object for your initial form state, which should include fields for the new password, a confirmation field, and the uid and token from the URL.

import { usePasswordConfirm } from "react-redux-django-auth";
import { useParams } from "react-router-dom";

const ResetPasswordConfirm = () => {
  const { uid, token } = useParams();
  const apiURL = process.env.REACT_APP_API_URL;

  const initialFormData = {
    new_password: "",
    re_new_password: "",
    uid: uid,
    token: token,
  };

  // ...
};

2. Call the Hook in Your Component

Call the usePasswordConfirm hook inside your functional component, passing the initialFormData and your API URL as arguments. The hook will return an object with all the necessary state and functions to build the form.

const { loading, formData, error, onChange, onSubmit, isStatus204 } =
  usePasswordConfirm(initialFormData, apiURL);

3. Connect the Returned Values to Your Form

Use the values returned from the hook to manage your form's state and behavior.

  • formData: Binds the input values to the form state.
  • onChange: A function that updates the form state as the user types.
  • onSubmit: Handles the form submission, dispatches the password confirmation action, and manages the loading state.
  • loading: A boolean value to disable the submit button during a network request.
  • error: Displays any authentication errors returned from the Redux state.
  • isStatus204: A boolean that becomes true upon a successful submission, useful for showing success messages or redirecting the user.
<form onSubmit={onSubmit}>
  {/* New Password Input */}
  <input
    type="password"
    name="new_password"
    onChange={onChange}
    value={formData.new_password}
    required
  />

  {/* Confirm New Password Input */}
  <input
    type="password"
    name="re_new_password"
    onChange={onChange}
    value={formData.re_new_password}
    required
  />

  {/* Submit Button */}
  <button type="submit" disabled={loading}>
    {loading ? "Confirming..." : "Reset Password"}
  </button>

  {/* Display Error Message */}
  {error && <div className="text-danger">{error}</div>}

  {/* Success Message (optional) */}
  {isStatus204 && <div className="text-success">Password has been reset!</div>}
</form>

useLogout Hook

The useLogout hook is a straightforward custom hook designed to handle user logout. Its sole purpose is to dispatch the Redux action that clears the user's authentication state, making it a clean and reusable way to handle logouts across your application.

1. Import the Hook

First, import the useLogout hook into the component where you need to provide a logout function, such as a navigation bar or a user profile dropdown.

import { useLogout } from "react-redux-django-auth";

2. Call the Hook in Your Component

Call the useLogout hook inside your functional component. It doesn't take any arguments and returns a single function that you can attach to an event handler, such as a button's onClick.

const UserProfile = () => {
  const logout = useLogout();

  // ...
};

3. Attach the Function to a Logout Button

Connect the logout function to a button or link that the user can click to sign out. When this function is called, it will dispatch the logout action to your Redux store, updating the application's authentication state.

const UserProfile = () => {
  const logout = useLogout();

  return (
    <div>
      <p>Welcome, User!</p>
      <button onClick={logout}>Log Out</button>
    </div>
  );
};

This approach simplifies your components by abstracting the Redux dispatch logic into a dedicated hook, keeping your UI code clean and focused on rendering.

useChangeAuthenticatedUserPassword Hook

The useChangeAuthenticatedUserPassword hook is a custom hook that simplifies the process of changing a user's password. It manages the form state for the current and new passwords, handles the loading state, and dispatches the necessary Redux action to update the password securely.

1. Import the Hook and Set Up Initial State

First, import the useChangeAuthenticatedUserPassword hook into your component. Define an object for your initial form state that includes fields for the current password, a new password, and a confirmation of the new password.

import { useChangeAuthenticatedUserPassword } from "react-redux-django-auth";

const initialFormData = {
  current_password: "",
  new_password: "",
  confirm_new_password: "",
};

2. Call the Hook in Your Component

Call the useChangeAuthenticatedUserPassword hook inside your functional component, passing the initialFormData and your API URL as arguments. The hook will return an object with all the state and functions needed to build the password change form.

const apiURL = process.env.REACT_APP_API_URL;

const ChangePasswordForm = () => {
  const { loading, formData, error, onChange, onSubmit, status } =
    useChangeAuthenticatedUserPassword(initialFormData, apiURL);

  // ... rest of your component logic
};

3. Connect the Returned Values to Your Form

Use the values returned from the hook to manage your form's state and behavior.

  • formData: Binds the input values to the form state.
  • onChange: A function that updates the form state as the user types.
  • onSubmit: Handles the form submission, including validation to ensure the new passwords match, and dispatches the password change action.
  • loading: A boolean value to disable the submit button while the API request is in progress.
  • error: Displays any validation errors (e.g., mismatched passwords) or authentication errors returned from the Redux state.
<form onSubmit={onSubmit}>
  {/* Current Password Input */}
  <input
    type="password"
    name="current_password"
    onChange={onChange}
    value={formData.current_password}
    required
  />

  {/* New Password Input */}
  <input
    type="password"
    name="new_password"
    onChange={onChange}
    value={formData.new_password}
    required
  />

  {/* Confirm New Password Input */}
  <input
    type="password"
    name="confirm_new_password"
    onChange={onChange}
    value={formData.confirm_new_password}
    required
  />

  {/* Submit Button */}
  <button type="submit" disabled={loading}>
    {loading ? "Changing..." : "Change Password"}
  </button>

  {/* Display Error Message */}
  {error && <div className="text-danger">{error}</div>}
</form>

Documentation for useAuthenticatedUser Hook

The useAuthenticatedUser hook is a central part of your authentication system, designed to manage the user's authentication status and profile data. It automatically checks authentication on page load or URL changes and provides functions to manually refresh the user's data or re-authenticate.

1. Import the Hook and Call It in Your Component

First, import the useAuthenticatedUser hook into a high-level component that needs access to the user's data, such as a layout component or a dashboard. You'll need to pass the apiURL and the current location (typically from react-router-dom) to the hook.

import { useAuthenticatedUser } from "react-redux-django-auth";
import { useLocation } from "react-router-dom";

const DashboardLayout = () => {
  const apiURL = process.env.REACT_APP_API_URL;
  const location = useLocation();

  const { isAuthenticated, currentUser, error, refreshUser } =
    useAuthenticatedUser(apiURL, location);

  // ...
};

2. Access the Returned Values

The hook returns a comprehensive object that you can use to conditionally render content, display user information, and handle errors.

  • isAuthenticated: A boolean (true, false, or null initially) that indicates if the user is authenticated.
  • currentUser: An object containing the user's profile data once it has been loaded.
  • error: Any authentication or profile-loading errors.
  • refreshUser: A function to manually re-fetch the user's profile data. This is useful for refreshing a profile after an update.
  • refreshAuth: A function to manually re-run the authentication check and then reload the user profile.
  • clearErrors: A function to manually clear any authentication-related errors from the Redux state.

3. Example Usage

You can use these values to build a dynamic and responsive UI. For instance, you can display a loading state, show different content for authenticated and unauthenticated users, and provide a way for the user to refresh their profile.

const DashboardLayout = () => {
  const apiURL = process.env.REACT_APP_API_URL;
  const location = useLocation();

  const { isAuthenticated, currentUser, error, refreshUser } =
    useAuthenticatedUser(apiURL, location);

  if (isAuthenticated === null) {
    // Show a loading state while the initial check is happening
    return <div>Checking authentication...</div>;
  }

  if (!isAuthenticated) {
    // Redirect to login or show a "Please log in" message
    return <Navigate to="/login" />;
  }

  // If isAuthenticated is true, currentUser will be available
  return (
    <div>
      {error && <div className="text-danger">{error}</div>}
      <h1>Welcome, {currentUser?.name}!</h1>
      <button onClick={refreshUser}>Refresh Profile</button>
      <nav>{/* Navigation links for authenticated users */}</nav>
      {/* Rest of your dashboard content */}
    </div>
  );
};