ReactJS Program to usePrevious Hook with Explanation
ReactJS
Medium
Hooks & Effects
28 views
1 min read
94 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around hook, previous, react. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a hook that returns the previous value and show it for a counter.
Input Format
No input.
Output Format
Render a React component.
Constraints
Store the previous value in a ref and update it in an effect.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
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>
);
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Create a hook that returns the previous value and show it for a counter.
Input / Output
Output
Render a React component.
Constraints
Store the previous value in a ref and update it in an effect.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Difficulty
Medium
ReactJS
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!