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 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?
Contents
CSS Animations Between Media Queries
CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during…
Vibration API
Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user. One of those simple APIs the Vibration API. The Vibration API allows developers to direct the device, using JavaScript, to vibrate in…
Multiple Background CSS Animations
CSS background animation has been a hot topic for a long time, mostly because they look pretty sweet and don’t require additional elements. I was recently asked if it was possible to have multiple background animations on a given element and the answer is yes…with…
Create WordPress Page Templates with Custom Queries
One of my main goals with the redesign was to make it easier for visitors to find the information that was most popular on my site. Not to my surprise, posts about MooTools, jQuery, and CSS were at the top of the list. What…
[ad_2]
Source link