Menu

gitpiper

usePrevious react Code Snippet in 2024

hooksstateeffectbeginner

Last Updated: 20 April 2024

Stores the previous state or props.

  • Create a custom hook that takes a value.
  • Use the useRef() hook to create a ref for the value.
  • Use the useEffect() hook to remember the latest value.
const usePrevious = value => { const ref = React.useRef(); React.useEffect(() => { ref.current = value; }); return ref.current; };
const Counter = () => { const [value, setValue] = React.useState(0); const lastValue = usePrevious(value); return ( <div> <p> Current: {value} - Previous: {lastValue} </p> <button onClick={() => setValue(value + 1)}>Increment</button> </div> ); }; ReactDOM.render(<Counter />, document.getElementById('root'));

react snippet similar to usePrevious For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️