Open In App

Implementing Undo & Redo Functionality in React Apps

Undo/Redo is a feature used frequently in various applications. React Hooks is a concept to handle and respond to the change of state in React Components.

In this article, we will try to implement the Undo/Redo functionality using react hooks thereby increasing your understanding and knowledge of various hooks.


Understanding the Undo & Redo Functionality:

Undo helps in removing the changes that the user has done by mistake or the changes that are no longer required. Redo is reverting the undo action. React Hooks such as useState() and useRef() will be used in this article to implement this functionality. useState() Hook is used to initialize and set the state variables and helps in data binding and useRef() hook responds to the changes in states and helps to track changes without re-rendering the component.

Approach to Implement Undo & Redo Functionality:

Steps to Implement Undo & Redo functionality in React App:

Step 1: Create a React App.

npx create-react-app my-react-app

Step 2: Switch to the project directory.

cd my-react-app

Project Strucutre:

Screenshot-2024-01-30-104510

Project Structure

Example: Below is an example of implementing Undo/Redo Functionality with React Hooks.

import React, {
    useState,
    useRef
} from 'react';
function App() {
    const [input, setInput] = useState("");
    const [inputArray, setInputArray] = useState([input]);
    const index = useRef(0);

    const undoFunction = () => {
        if (index.current > 0) {
            index.current = index.current - 1;
            setInput(inputArray[index.current]);
        }
    };

    const redoFunction = () => {
        if (index.current < inputArray.length - 1) {
            index.current = index.current + 1;
            setInput(inputArray[index.current]);
        }
    };

    const handleInputChange = (e) => {
        const newValue = e.target.value;
        setInput(newValue);
        index.current = index.current + 1;
        setInputArray(
            [...inputArray.slice(0, index.current), newValue]
        );
    };

    return (
        <div>
            <h1>Value: {input}</h1>
            <button onClick={undoFunction}
                disabled={index.current === 0}>
                UNDO
            </button>
            <button onClick={redoFunction}
                disabled={index.current === inputArray.length - 1}>
                REDO
            </button>
            <input type="text"
                value={input} onChange={handleInputChange} />
        </div>
    );
}

export default App;

Output:

output

OUTPUT FOR UNDO REDO APP GIVEN IN ABOVE CODE SNIPPET


Article Tags :