Skip to main content

Command Palette

Search for a command to run...

Performing an action with state after setting state (useState)

Published
2 min read
Performing an action with state after setting  state (useState)
P

I am a JavaScript software developer that specializes in building User friendly interfaces that helps solve business problems and meet users' needs

In react functional components, state is managed by the useState hook. This hook returns an array of two elements. One is the state, and the second element is the state setter function.

One major caveat of the state setter function is that it is asynchronous. Meaning that it doesn't complete its operation instantaneously. Therefore, trying to access the new state immediately after setting the state's value might be quite a headache.

import React, { useState } from "react";

const Counter = () => {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount((prev) => prev + 1);
    console.log(count);
  };

  return (
    <div>
      <h1>COUNTER</h1>
      <button onClick={incrementCount}>INCR</button>
    </div>
  );
};

export default Counter;

If you run the above code, you will notice that when you click the button to call the increment count function, the value 0 is logged to the console. The state changed but JavaScript didn't wait, for the setCount function to be executed before proceeding with the console.log(...). Things like this can cause unwanted behaviour in our code.

To tackle this, all we need to do is make use of the useEffect hook. The useEffect hook can be used to watch the value of certain variables or state and then perform an action based on that. So what we do here is pass the state we want to be watched into the useEffect's dependency array, then perform our desired action in the callback of the useEffect.

Here's what I mean:

  const incrementCount = () => {
    setCount((prev) => prev + 1);
  };

  useEffect(() => {
    console.log(count);
  }, [count]);

This way, console.log(count) only runs after the value of count has been successfully mutated.

If you have any more questions about this article or the useState hook, please be free to ask me in the comments section. Follow me for more tips and tutorials regarding Web development.

More from this blog

Prophet Bestman

16 posts

I am a software developer that employs the use of ReactJS, NextJS, JavaScript, NodeJS and more to build software solutions