Photo by Brook Anderson on Unsplash

Simplicity with Hooks

React Hooks have moved the needle as far as develpment goes in the React ecosystem. They are really great to use and easy to understand.

However they do come with their own set of gotcha's. For example did you know that you can pass a function to the set method of useState in order to get the previous state? This is very much like you would do with setState in the days of Class components. You can see below instead of grabbing the count from the count variable above I am doing a very small function call to get the previous state before returning the updated value.

This also has benefits such as if you are passing down the set method you don't need to rely on also passing down the value just to have it to update with.

import { useState } from "react" function Component() { const [count, setCount] = useState(0) return ( <div> <button onClick={() => setCount(count => count + 1)}>{count}</button> </div> ) }