What’s with functions inside setState?

Photo by Marliese Streefland on Unsplash

setState is asynchronous

const [ count, setCount ] = useState(3)const onClick = () => {
setCount(5)
console.log(count) // first click will print out 3
}
return(<button onClick={onClick}> hello </button>)

The problem

const [ count, setCount ] = useState(0)
const onClick = () => {
setCount(count + 1)
}
return(
<div>
<span> { count } </span>
<button onClick={onClick}> increment! </button>
</div>
)
// let's say count is 5
setCount(count + 1) // count is 5, becomes 6
setCount(count + 1) // count is still 5, becomes 6
// re-renders, count becomes 6

The Solution

// let's say count is 5
setCount(current => current + 1) // current is 5, becomes 6
setCount(current => current + 1) // current is 6, becomes 7
// re-renders, count becomes 7

More depth

// let's say count is 5
setCount(count + 1) --> setCount(6)
setCount(count + 1) --> setCount(6)
// re-renders, count becomes 6
// let's say count is 5
setCount(current => current + 1) --> setCount(5 => 5 + 1)
setCount(current => current + 1) --> setCount(6 => 6 + 1)
// re-renders, count becomes 7

--

--

--

Writing is my way to express self-growth & understanding over a topic or concept.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Create a ReactJS client with Auth0 for a Serverless application (using Custom Authorizers)

How to Validate JavaScript Object Better with TypeScript

Filters: How Nest JS Handle Exceptions

Simple shop app using Node.js and React

That shouldn’t work! Oh, Vue binds all methods?

Create Custom HTML Element without any Frontend Framework

Leetcode Q124. Binary Tree Maximum Path Sum

Build A Login Page with FirebaseUI for Vue in 20 mins

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
nashe omirro

nashe omirro

Writing is my way to express self-growth & understanding over a topic or concept.

More from Medium

How to make a table in React with Hooks

How to Use Redux Middleware to Better Control Your Data and Write Cleaner Code

HOW TO CREATE A NEW COMPONENT IN REACT / REACTJS

Prop techniques for React