Forms of the future with Zustand and Zod

Kabeer Jaffri — 2 minute read 20th Feb, 2024

Forms are a crucial part of user interactions on the web, and their design plays a significant role in shaping the overall user experience.

In this article, we'll explore how Zustand and Zod can be leveraged to create dynamic, beautiful, and highly reactive forms. By integrating real-time validation and feedback, paired with popular UI libraries like Material UI, we can elevate form design to the next level.

Zustand and Zod: A Powerful Duo: Zustand is a small, fast, and scalable state management library for React. It provides a simple API for creating global state in your application, making it perfect for managing form state.

On the other hand, Zod is a TypeScript-first schema declaration and validation library, enabling us to define strict data structures and validate form inputs with ease.

Lets create a sample form.

Building a Sign-In Form: Let's take a closer look at a sample implementation of a sign-in form using Zustand and Zod. This form includes features like email validation, existence checking in the database, and real-time feedback to users. Reactivity: The form dynamically reacts to user input, updating the state and triggering validation functions in real-time.



// store.js
import { create } from 'zustand';
            
export const useFormState = create((set) => ({
    email: '',
    password: '',
    // Add other form fields and state properties as needed

    setEmail: (email) => set({ email: email.toString().toLowerCase().trim() }),
    setPassword: (password) => set({ password: password.toString().toLowerCase().trim() }),
    // Add other set methods for different form fields

    // Bind these properties to icon states in JSX components 
    email_verified: false,
    password_verified: false,

    // Bind these functions to onBlur, onFocus events to trigger validation
    validateEmail: () => set({ email_verified: /** Email verificaton logic **/ }),
    validatePassword: () => set({ password_verified: /** Password verificaton logic **/ }),
}));

Email and password inputs are validated against predefined rules, providing instant feedback on the form's validity.
The form checks the existence of the provided email in the database, enhancing security and user experience. Integrating popular UI libraries such as Material UI can add a polished and visually appealing touch to the form. Leverage Material UI's indicators, icons, and styling components to create a seamless and aesthetically pleasing user interface.

Sign-In Form Implementation.

Implementing a simple form using the previous concepts, in JSX with native react components, this is easily portable to use libraries like Material or Chakra.

// SignInForm.js
import React from 'react';
import { useFormState } from './store';
        
const SignInForm = () => {
    const { email, password, setEmail, setPassword, validateEmail, validatePassword } = useFormState();
        
    return (
        <form>
            {/* Render your form fields, buttons, and UI components here, optionally render checkmark icons and borders */}
            <input 
                type="text" 
                value={email} 
                onChange={(e) => setEmail(e.target.value)} 
                onBlur={validateEmail} 
            />
            <input 
                type="password" 
                value={password} 
                onChange={(e) => setPassword(e.target.value)} 
                onBlur={validatePassword} 
            />
        </form>
    );
};

export default SignInForm;
Setting Up Your Project
  1. Installing zustand npm install zustand

  2. Set up Material UI using npm install @mui/core

Usage in App Component:

// App.js
import React from 'react';
import SignInForm from './SignInForm';
        
const App = () => {
    return (
        <div>
            <h1>Zustand and Material UI Form Example</h1>
            <SignInForm />
        </div>
    );
};

export default App;

Ensure to customize the components and styles according to your project's needs. This approach provides a clean and organized way to manage state and styles using Zustand and Material UI.