This React interview question sounds simple…but it often reveals how well someone understands hooks 👀 “How would you access the previous state or prop in React?” React doesn’t provide a built-in usePrevious hook. Solving this correctly comes down to understanding how values persist across renders. The core idea 👇 ➡️ useRef stores a value without triggering re-renders ➡️ useEffect updates it after each render ➡️ Together, they expose the last rendered value That’s exactly what this custom usePrevious hook does. Why this hook matters 🔥 ➡️ Common React interview pattern ➡️ Clean way to compare current vs previous values ➡️ Useful for counters, animations, forms, and UI transitions ➡️ Avoids unnecessary state and extra renders ➡️ Reusable and readable I’ve attached a clean code snippet image 👇 Hook + simple counter demo. Note: This is a foundational implementation...ideal for learning and interviews, and easy to extend. 💬 BTW Have you ever needed the previous value in a real project? How did you handle it? Don't forget to share your thoughts in the comments below ⬇️ Happy coding 💙 #React #JavaScript #CustomHooks #ReactHooks #Frontend #WebDevelopment #Interviews
Hi Bahnisikha Dhar, I’m preparing for frontend roles and admire your experience. Sent you a connection request—would be grateful to connect and learn from your experience.
import { useState, useEffect, useRef } from "react" function Counter() { const [count, setCount] = useState(0) const prevCount = useRef(count) useEffect(() => { prevCount.current = count }, [count]) return ( <div> <p>Current: {count}</p> <p>Previous: {prevCount.current}</p> <button onClick={() => setCount(count + 1)}>+</button> </div> ) } This is not enough ? Do we need that custom hook ?