This content originally appeared on David Walsh Blog and was authored by David Walsh
Hooks are essential for the functional component pattern in React. One frequent logic comparison with class components was comparing a previous prop value with a current prop value via lifecycle methods. So what’s an easy pattern for duplicating previous value comparisons in functional components?
The useRef and useEffect hooks allow us manage that same functionality in functional components via a custom hook — usePrevious:
import { useEffect, useRef } from 'react';
export function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
// Usage
export function MyComponent(props) {
const { name } = props;
const previousName = usePrevious(name);
if(name != previousName) {
// Do something
}
}
I love this usePrevious hook, if only because I frequently forget to use the .current property and it helps avoid some boilerplate code. What are your thoughts on this pattern? Do you have any custom hooks you rely on?
The post React usePrevious Hook appeared first on David Walsh Blog.
This content originally appeared on David Walsh Blog and was authored by David Walsh
David Walsh | Sciencx (2021-08-23T14:00:13+00:00) React usePrevious Hook. Retrieved from https://www.scien.cx/2021/08/23/react-useprevious-hook/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.