🚨 A small TypeScript mistake I still see in React projects Many developers type their state setters as - (val: number) => void. It looks correct - but it silently breaks a core React feature. React state setters don't just accept a value - they also accept a function. This is essential when your next state depends on the previous one. If you type the setter wrong, functional updates won't typecheck. You've locked yourself out of a feature React gives you for free - and opened the door to subtle bugs. Typing setters correctly means: React's full API stays intact, refactors are safer across your codebase, and state bugs from stale closures become much harder to introduce. It's one line of types. But in a large codebase, it's the difference between code that works and code that works until it doesn't. If you use TypeScript with React, don't throw this away. #TypeScript #React #JavaScript #Frontend #CodingTips
In early days , I made the same mistake. A quick tip woule be :- on hovering over the setters , we get the inferred types. Just copy it when you are trying to pass around the setters.
Yes, that’s technically correct but I’m not going to write it out like that every single time. I just define a generic once: type StateSetter<T> = React.Dispatch<React.SetStateAction<T>>; Then I use it like this: type Props = { setCount: StateSetter<number>; };
Eh, I usually pass the handler down as a prop, not the raw setter.
Strong point. Incorrect setter typing removes one of React’s safest patterns and you won’t notice until a stale state bug hits production.
TypeScript, saving you from bugs you didn’t even know you were about to write
Such a small detail, but huge impact in real projects. Functional updates are easy to overlook. Great reminder.
Good point. Minimal types. Maximum regret hahah
Thanks! I never thought about this little detail yet it can save much time from wondering why does this show type error. Will do!
As much as i agree with the correctness argument here, this doesn’t affect React at all. Dispatch<SetStateAction<T>> essentially evaluates to () => void; anyway, and the types stripped when you build.