This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Handling Undo/Redo in a form

  • ReactJS
  • July 1, 2025

Share On :

Introduction

An undo/redo functionality in the form building area can be more useful for the end user, particularly when applications are complex and users do many changes and might want to undo some actions. In this comprehensive guide, we are going to see how to implement solid undo/redo functionality for React forms.

Prerequisites
  • React Fundamentals 

  • State Management in React

  • Form Development with Material-UI

  • JavaScript / TypeScript concepts

Why Undo/Redo Matters in Forms

Form interactions can be complex, and users often make mistakes or change their minds. Undo/redo functionality provides :

  • Error Recovery : Users can quickly revert accidental changes

  • Confidence : Knowing they can undo changes encourages users to experiment

  • Efficiency : Faster than manually reverting multiple field changes

  • Professional UX : Makes your application feel more polished and user-friendly

Core Concepts
  • State History Management

The foundation of undo/redo is maintaining a history of form states. Each significant change creates a new entry in the history stack, allowing navigation between different versions of the form data.

  • Command Pattern Implementation

Each user action becomes a reversible command that knows how to execute and undo itself. This creates clean separation between actions and their effects.

  • Memory Optimization

Since form data can be large, we need strategies to prevent memory bloat while maintaining sufficient history depth.

Code Implementation

Let’s create a React app using the following steps :

				
					//Create a react app using the following command
npm create vite@latest  undo-redo-in-form --template react-ts
cd  undo-redo-in-form
npm install 

//Install the Material UI library
npm install @mui/material @emotion/react @emotion/styled

//Command for run the React project
npm run dev

				
			

Step-1 : Folder Structure :

folder-structure

Step-2 : Custom Hook Approach :

Let us implement a custom hook in React that can assist our state management for form histories and provide undo/redo actions. We will divide this as follows :

  • State Management : We will keep two pieces of state: one for the form-data history and another for the current position (or index) in the history stack.
  • Persistence : The state should be persisted via localStorage so that even after the user refreshes, the history can still be accessed.
  • Undo/Redo : Functions for traversing backwards and forwards through history.
				
					//useHistory.ts

import { useState, useEffect } from "react";

const useHistory = <T extends object>(
  formData: T,
  setFormData: React.Dispatch<React.SetStateAction<T>>
) => {
  const [history, setHistory] = useState<T[]>([formData]);
  const [historyIndex, setHistoryIndex] = useState<number>(0);

  useEffect(() => {
    const savedHistory = localStorage.getItem("formHistory");
    const savedIndex = localStorage.getItem("historyIndex");

    if (savedHistory && savedIndex !== null) {
      const parsedHistory: T[] = JSON.parse(savedHistory);
      const parsedIndex = Number(savedIndex);
      setHistory(parsedHistory);
      setHistoryIndex(parsedIndex);
      setFormData(parsedHistory[parsedIndex]);
    }
  }, []);

  useEffect(() => {
    localStorage.setItem("formHistory", JSON.stringify(history));
    localStorage.setItem("historyIndex", historyIndex.toString());
  }, [history, historyIndex]);

  const setState = (newState: T): void => {
    const updatedHistory = [...history.slice(0, historyIndex + 1), newState];
    setHistory(updatedHistory);
    setHistoryIndex(updatedHistory.length - 1);
    setFormData(newState);
  };

  const undo = () => {
    if (historyIndex > 0) {
      const newIndex = historyIndex - 1;
      setHistoryIndex(newIndex);
      setFormData(history[newIndex]);
    }
  };

  const redo = () => {
    if (historyIndex < history.length - 1) {
      const newIndex = historyIndex + 1;
      setHistoryIndex(newIndex);
      setFormData(history[newIndex]);
    }
  };

  const undoAll = () => {
    setHistoryIndex(0);
    setFormData(history[0]);
  };

  const redoAll = () => {
    const lastIndex = history.length - 1;
    setHistoryIndex(lastIndex);
    setFormData(history[lastIndex]);
  };

  const updateNestedState = (path: string, value: any): void => {
    const newState: T = JSON.parse(JSON.stringify(formData));
    const keys = path.split(".");
    let temp: any = newState;

    for (let i = 0; i < keys.length - 1; i++) {
      temp = temp[keys[i]];
    }

    temp[keys[keys.length - 1]] = value;
    setState(newState);
  };

  return {
    setState,
    undo,
    redo,
    undoAll,
    redoAll,
    updateNestedState,
  };
};

export default useHistory;

				
			

Step-3 : Form Component Implementation

				
					//Form.tsx
import React, { useState } from "react";
import {
  Box,
  TextField,
  Button,
  Typography,
  RadioGroup,
  FormControlLabel,
  Radio,
  Checkbox,
  Select,
  MenuItem,
  InputLabel,
  FormControl,
  FormGroup,
  TextareaAutosize,
  Stack,
} from "@mui/material";
import useHistory from "../hooks/useHistory";

interface FormData {
  name: string;
  email: string;
  address: {
    city: string;
  };
  gender: string;
  skills: string[];
  country: string;
  bio: string;
}

const Form: React.FC = () => {
    const initialFormData: FormData = {
    name: "",
    email: "",
    address: { city: "" },
    gender: "",
    skills: [],
    country: "",
    bio: "",
  };

  const [formData, setFormData] = useState<FormData>(initialFormData);

  const {
    setState,
    undo,
    redo,
    undoAll,
    redoAll,
    updateNestedState,
  } = useHistory<FormData>(formData, setFormData);

  //For skills section 
  const handleCheckboxChange = (skill: string) => {
    const updatedSkills = formData.skills.includes(skill)
      ? formData.skills.filter((s) => s !== skill)
      : [...formData.skills, skill];
    setState({ ...formData, skills: updatedSkills });
  };

   // Reset undo/redo history with cleared form
   const handleSubmit = () => {
    console.log("Form Submitted:", formData);
    setFormData(initialFormData);
    setState(initialFormData); 
  };

  return (
    <Box sx={{ maxWidth: 600, margin: "auto", p: 4 }}>
      <Typography variant="h4" gutterBottom>
        User Registration Form
      </Typography>

      <Stack spacing={3}>
        <TextField
          fullWidth
          label="Name"
          value={formData.name}
          onChange={(e) => setState({ ...formData, name: e.target.value })}
        />

        <TextField
          fullWidth
          label="Email"
          type="email"
          value={formData.email}
          onChange={(e) => setState({ ...formData, email: e.target.value })}
        />

        <TextField
          fullWidth
          label="City"
          value={formData.address.city}
          onChange={(e) => updateNestedState("address.city", e.target.value)}
        />

        <Box>
          <Typography variant="subtitle1">Gender</Typography>
          <RadioGroup
            row
            value={formData.gender}
            onChange={(e) => setState({ ...formData, gender: e.target.value })}
          >
            <FormControlLabel value="male" control={<Radio />} label="Male" />
            <FormControlLabel value="female" control={<Radio />} label="Female" />
          </RadioGroup>
        </Box>

        <Box>
          <Typography variant="subtitle1">Skills</Typography>
          <FormGroup row>
            {["React", "Node", "CSS", "JavaScript"].map((skill) => (
              <FormControlLabel
                key={skill}
                control={
                  <Checkbox
                    checked={formData.skills.includes(skill)}
                    onChange={() => handleCheckboxChange(skill)}
                  />
                }
                label={skill}
              />
            ))}
          </FormGroup>
        </Box>

        <FormControl fullWidth>
          <InputLabel>Country</InputLabel>
          <Select
            value={formData.country}
            label="Country"
            onChange={(e) => setState({ ...formData, country: e.target.value })}
          >
            <MenuItem value="India">India</MenuItem>
            <MenuItem value="USA">USA</MenuItem>
            <MenuItem value="UK">UK</MenuItem>
          </Select>
        </FormControl>

        <FormControl fullWidth>
          <TextareaAutosize
            minRows={4}
            placeholder="Bio"
            value={formData.bio}
            onChange={(e) => setState({ ...formData, bio: e.target.value })}
            style={{ width: "100%", padding: 10, fontSize: 16 }}
          />
        </FormControl>

        <Stack direction="row" spacing={2}>
          <Button variant="outlined" onClick={undo}>
            Undo
          </Button>
          <Button variant="outlined" onClick={redo}>
            Redo
          </Button>
          <Button variant="contained" onClick={undoAll}>
            Undo All
          </Button>
          <Button variant="contained" onClick={redoAll}>
            Redo All
          </Button>
        </Stack>
        <Button variant="contained" color="primary" onClick={handleSubmit}>
            Submit
        </Button>
      </Stack>
    </Box>
  );
};

export default Form;

				
			

With the above code, you will get the following output on your screen.

output
Conclusion

Implementing undo/redo functionality in React forms enhances user experience significantly. The key is to balance functionality with performance, provide clear visual feedback, and ensure the implementation is intuitive for users.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.
Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

March 12, 2025
Implementing backend pagination with Material-UI in React
Implementing backend pagination with Material-UI in React
June 25, 2025
How Lockfiles Ensure Stability and How to Read Them
June 26, 2025
Semantic Versioning (^, ~,  *): What Most Devs Misunderstand
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform User-Friendly, Secure and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 6, 2023
Collaborative Blogging Platform for Businesses, Authors, and Readers
Collaborative Blogging Platform for Businesses, Authors, and Readers
October 4, 2023
Telemedicine Appointment & Health Record Portal
Telemedicine Appointment & Health Record Portal

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram