React usePrevious Hook

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 […]

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

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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » React usePrevious Hook." David Walsh | Sciencx - Monday August 23, 2021, https://www.scien.cx/2021/08/23/react-useprevious-hook/
HARVARD
David Walsh | Sciencx Monday August 23, 2021 » React usePrevious Hook., viewed ,<https://www.scien.cx/2021/08/23/react-useprevious-hook/>
VANCOUVER
David Walsh | Sciencx - » React usePrevious Hook. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/23/react-useprevious-hook/
CHICAGO
" » React usePrevious Hook." David Walsh | Sciencx - Accessed . https://www.scien.cx/2021/08/23/react-useprevious-hook/
IEEE
" » React usePrevious Hook." David Walsh | Sciencx [Online]. Available: https://www.scien.cx/2021/08/23/react-useprevious-hook/. [Accessed: ]
rf:citation
» React usePrevious Hook | David Walsh | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.