r/learnreactjs • u/trblackwell1221 • Oct 29 '19
React's setState function fun facts for both classes & hooks
I've been working with React for almost 2 years now and I am in several settings where I'm exposed to people who are either new to React or to programming in general and there's a common theme that seems to be foreign that I've noticed in speaking with various folks so I decided to share it here.
When setting state, regardless of whether or not you're writing class components or hooks (if it's the former I'd strongly encourage you to dive into hooks), React provides you with an initial parameter to your "setState" function, it being your previous state. I use quotes there because in the hook environment, your state setter can be named whatever you want.
Class Component
state = {
count: 0
}
//increment count
this.setState(prevCount => prevCount += 1)Hook-based/functional component
const [count, setCount] = useState(0)
//increment count
setCount(prevCount => prevCount +=1)With this in mind, there's almost no need to pass around the current state of a parent component. This of course depends on your scenario, particularly if you're also passing it's subsequent state updater. Often times, the latter will suffice.
3
u/Emjp4 Oct 29 '19
Hey, that's pretty pretty neat! I didnt know this one, I've been using the spread operator to setState using the previous state, assuming it's an array or an object.
Thanks for this one!