Skip to content

Instantly share code, notes, and snippets.

@DeVoresyah
Created October 14, 2021 10:55
Show Gist options
  • Save DeVoresyah/79fd552b5fd74b4c009778c7183c5770 to your computer and use it in GitHub Desktop.
Save DeVoresyah/79fd552b5fd74b4c009778c7183c5770 to your computer and use it in GitHub Desktop.
usePrevious React Hook
import React, { useState } from "react";
import usePrevious from "./usePrevious";
const App = () => {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return (
<>
<p>Count: {count} - Previous Count: {prevCount || 0}</p>
<button onClick={() => setCount(count + 1)}>Add</button>
</>
);
};
import { useEffect, useRef } from "react";
export default (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment