How to use TypeScript to validate SetState Functions and Event Handlers
Early bugs detection is crucial in programming, and in React, this is especially important when passing a setter function to a component or using an event handler.
First, it's important to understand that useState is a hook in React used to store and modify variables. It's used to define the re-render process and returns an array containing two values:
1- The current state
2- The function used to change the current state - setFunc
When passing a setFunc function, it's essential to specify its function and return value. This is done using:
React.Dispatch<React.SetStateAction
typescript1import React, { Dispatch, SetStateAction } from 'react'; 2 3interface ChildProps { 4// Replace 'string' with whatever your state type is 5 6setCount: Dispatch<SetStateAction<number>>; 7} 8 9const Child = ({ setCount }: ChildProps) => { 10return <button onClick={() => setCount((prev) => prev + 1)}>Increment</button>; 11 12}; 13
In the case of event handlers such as onClick, onClose, onSubmit, etc., you need to specify the arguments the function expects and what it will return.
For functions that return nothing, void is used.
For inputs, the following is used:
typescript1interface { 2onChange:(event:React.ChangeEvent<HTMLInputElement>) => void 3} 4
For Mouse events like onClick:
typescript1interface { 2onClick:(event:React.MouseEvent<HTMLButtonElement>) => void 3} 4

React & Next.js Front-end Developer