In React class-based components we have this callback that would run after the state has been updated.
1import React, { Component } from 'react'; 2 3class App extends Component { 4 constructor(props) { 5 super(props); 6 this.state = { 7 beer: 0, 8 }; 9 } 10 11 updateBeerCount = value => { 12 this.setState({ beer: value}, ()=>{ 13 console.log('count updated!, I\'m the callback'); 14 }); 15 }; 16 17 render() { 18 return ( 19 <div> 20 <p>Try increasing the number and check your console!</p> 21 <input 22 type="number" 23 value={this.state.beer} 24 onChange={e => this.updateBeerCount(e.target.value)} 25 /> 26 </div> 27 ); 28 } 29 30} 31 32export default App;
But in functional components, we don't have any such callback function in useState hook. However, you can achieve this in a cleaner way using useEffect hook with correct dependencies. Check the example below:
1import React, { useState, useEffect } from "react"; 2 3const App = () => { 4 const [beerCount, setBeerCount] = useState(0); 5 6 useEffect(() => { 7 console.log("count updated! this is run after update!"); 8 }, [beerCount]); // run whenever beerCount is changed 9 10 return ( 11 <input 12 type="number" 13 value={beerCount} 14 onChange={e => setBeerCount(e.target.value)} 15 /> 16 ); 17}; 18 19export default App;
Let's connect:
Linkedin: https://www.linkedin.com/in/mubbashir10/
Twitter: https://twitter.com/mubbashir100