DEV Community

Mubbashir Mustafa
Mubbashir Mustafa

Posted on • Edited on

Callback solution for useState hook in React

In React class-based components we have this callback that would run after the state has been updated.

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      beer: 0,
    };
  }

  updateBeerCount = value => {
    this.setState({ beer: value}, ()=>{
      console.log('count updated!, I\'m the callback');
    });
  };

  render() {
    return (
      <div>
        <p>Try increasing the number and check your console!</p>
        <input
          type="number"
          value={this.state.beer}
          onChange={e => this.updateBeerCount(e.target.value)}
        />
      </div>
    );
  }

}

export default App;
Enter fullscreen mode Exit fullscreen mode

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:

import React, { useState, useEffect } from "react";

const App = () => {
  const [beerCount, setBeerCount] = useState(0);

  useEffect(() => {
    console.log("count updated! this is run after update!");
  }, [beerCount]); // run whenever beerCount is changed

  return (
    <input
      type="number"
      value={beerCount}
      onChange={e => setBeerCount(e.target.value)}
    />
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Let's connect:

Linkedin: https://www.linkedin.com/in/mubbashir10/

Twitter: https://twitter.com/mubbashir100

Top comments (2)

Collapse
 
rajeshroyal profile image
Rajesh Royal

good one but can't satisfy the need, It can't be reliable.

Collapse
 
harshjoeyit profile image
Harshit Gangwar

I am new to React and learning.
Please explain the pitfalls of this implementation?