usePrevious Hook
ReactJS
Medium
6 views
Problem Description
Create a hook that returns the previous value and show it for a counter.
Output Format
Render a React component.
Constraints
Store the previous value in a ref and update it in an effect.
Official Solution
import React, { useEffect, useRef, useState } from 'react';
function usePrevious(value) {
const ref = useRef(value);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
export default function App() {
const [count, setCount] = useState(0);
const prev = usePrevious(count);
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode counter</h2>
<div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
<button type='button' onClick={() => setCount((c) => c + 1)} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>+</button>
<div style={{ color: '#555' }}>Prev: {prev} | Now: {count}</div>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!