usePrevious Value Hook
ReactJS
Medium
6 views
Problem Description
Create a small hook that returns the previous value of a prop/state.
Output Format
Render a React component.
Constraints
Use 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 [n, setN] = useState(0);
const prev = usePrevious(n);
return (
<div style={{ padding: 16 }}>
<strong>meetcode previous value</strong>
<div style={{ marginTop: 8 }}>Now: {n}</div>
<div style={{ color: '#555' }}>Previous: {prev}</div>
<button type='button' onClick={() => setN((x) => x + 1)} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Increase</button>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!