Wednesday, April 5, 2023
HomeProgrammingReact usePrevious Hook

React usePrevious Hook


Hooks are important for the useful element sample in React. One frequent logic comparability with class elements was evaluating a earlier prop worth with a present prop worth by way of lifecycle strategies. So what’s a straightforward sample for duplicating earlier worth comparisons in useful elements?

The useRef and useEffect hooks permit us handle that very same performance in useful elements by way of a customized hook — usePrevious:

import { useEffect, useRef } from 'react';

export perform usePrevious(worth) {
  const ref = useRef();
  useEffect(() => {
    ref.present = worth;
  }, [value]);
  return ref.present;
}

// Utilization
export perform MyComponent(props) {
  const { title } = props;
  const previousName = usePrevious(title);

  if(title != previousName) {
    // Do one thing
  }
}

I like this usePrevious hook, if solely as a result of I steadily neglect to make use of the .present property and it helps keep away from some boilerplate code. What are your ideas on this sample? Do you’ve any customized hooks you depend on?

  • Welcome to My New Office

    My first skilled net improvement was at a small print store the place I sat in a windowless cubical all day. I suffered that boxed in atmosphere for nearly 5 years earlier than I used to be capable of finding a distant job the place I labored from residence. The primary…

  • Page Visibility API

    One occasion that is all the time been missing inside the doc is a sign for when the person is a given tab, or one other tab. When does the person change off our website to take a look at one thing else? When do they arrive again?


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments