In a React app, we often need to pass a state and its setter to another function. I found defining this interface in a React project is quite helpful:
interface ReactStateAndSetter<T> {
state: T;
setter: React.Dispatch<React.SetStateAction<T>>;
}
When we need to pass a React state and its setter to a function, we can let the function accept such an object that is compatible with this interface:
function myFunction(stateAndSetter: ReactStateAndSetter<number>) {
// ...
}
function App() {
const [counter, setCounter] = useState<number>(0);
myFunction({ state: counter, setter: setCounter });
}