usePreviousHook
You have to build a simple Counter App in React that also shows the previous count value. The goal is to allow users to increase, decrease, or reset the counter using buttons. In addition to displaying the current count, the app should also show the previous count using a custom usePrevious hook.
Things To Do
State Management
Use the useState hook to keep track of the current count value.
const [currentCount, setCurrentCount] = useState(0);
The initial value of the count should be 0.
Previous State Hook
Create a custom hook usePrevious to store the previous value of the count.
The hook should return undefined on the first render, and return the previous value after each update.
const previousCount = usePrevious(currentCount);
Button Functionality
-
Implement the
incrementfunction to increase the count by 1. -
The button should be labeled Increment.
-
Implement the
decrementfunction to decrease the count by 1. -
The button should be labeled Decrement.
-
Implement the
resetfunction to set the count back to 0. -
The button should be labeled Reset.
Display Output
Show the current count inside a heading element:
Current Count: {currentCount}
Show the previous count (using the usePrevious hook) in a separate heading element:
Previous Count: {previousCount}
Companies:
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
