No intro! Let's learn how to get the prevState values using react hooks.
I will create a button that increases count value showing previous and current count value using react hooks.
For the final code, go to the end of the post.
Create a react app:
npx create-react-app myapp
Then, move to the newly created project and hit
npm start
Open up your browser and enter the link below
http://localhost:3000
You should see something like this:
Now, open the project in your favorite text editor.
Now, edit the App.js and make a button that increases a value of count. So the App.js will look like this.
function App() {
const [count, setCount] = React.useState(0)
const _increaseCount = () => {
setCount(count + 1)
}
return (
<div className="App">
<div>Current Count Value: {count}</div>
<button onClick={_increaseCount}>Increase Count</button>
</div>
);
}
After saving, you will see an update in your browser:
Now, create a custom hook usePrevious
that will return the previous state value of any parameter passed into it.
//custom Hook
function usePrevious(data){
const ref = React.useRef();
React.useEffect(()=>{
ref.current = data
}, [data])
return ref.current
}
And get previous state count value as:
var prevCount = usePrevious(count)
Then, use the prevCount
variable inside the return statement as:
<div>Previous Count Value: {prevCount}</div>
So, now the job is done and app should look like below and you should be able to see previous and current state count values.
Final code for App.js would look like this:
import React from 'react';
import './App.css';
//custom Hook
function usePrevious(data){
const ref = React.useRef();
React.useEffect(()=>{
ref.current = data
}, [data])
return ref.current
}
function App() {
const [count, setCount] = React.useState(0)
const _increaseCount = () => {
setCount(count + 1)
}
const prevCount = usePrevious(count)
return (
<div className="App">
<div>Previous Count Value: {prevCount}</div>
<div>Current Count Value: {count}</div>
<button onClick={_increaseCount}>Increase Count</button>
</div>
);
}
export default App;
Here is youtube video doing the same stuff:
YouTube:
Feedbacks appreciated...
Top comments (0)