title: Canvas Freehand drawing Undo and Redo functionality in Reactjs
body: <p>After my attempt to creating a Freehand drawing using HTML5 canvas implemented using React, I want to proceed to Add an undo and redo functionality onclick of the undo and redo button respectively. I'll be grateful for any help rendered.</p>
  <pre><code>function App(props) {
      const canvasRef = useRef(null);
      const contextRef = useRef(null);
      const [isDrawing, setIsDrawing] = useState(false);
  
      useEffect(() =&gt; {
          const canvas = canvasRef.current;
          canvas.width = window.innerWidth * 2;
          canvas.height = window.innerHeight * 2;
          canvas.style.width = `${window.innerWidth}px`;
          canvas.style.height = `${window.innerHeight}px`;
  
          const context = canvas.getContext('2d');
          context.scale(2, 2);
          context.lineCap = 'round';
          context.strokeStyle = 'black';
          context.lineWidth = 5;
          contextRef.current = context;
      }, []);
  
      const startDrawing = ({ nativeEvent }) =&gt; {
          const { offsetX, offsetY } = nativeEvent;
          contextRef.current.beginPath();
          contextRef.current.moveTo(offsetX, offsetY);
          setIsDrawing(true);
      };
  
      const finishDrawing = () =&gt; {
          contextRef.current.closePath();
          setIsDrawing(false);
      };
  
      const draw = ({ nativeEvent }) =&gt; {
          if (!isDrawing) {
              return;
          }
          const { offsetX, offsetY } = nativeEvent;
          contextRef.current.lineTo(offsetX, offsetY);
          contextRef.current.stroke();
      };
  
      return &lt;canvas onMouseDown={startDrawing} onMouseUp={finishDrawing} onMouseMove={draw} ref={canvasRef} /&gt;;
     
  }
  </code></pre>