import { useState, useCallback } from "react"; export default function useStateWithValidation( validationFunc: (value: T) => boolean, initialValue: T ): [T, (nextState: T | ((prevState: T) => T)) => void, boolean] { const [state, setState] = useState(initialValue); const [isValid, setIsValid] = useState(() => validationFunc(state)); const onChange = useCallback( (nextState: T | ((prevState: T) => T)) => { const value = typeof nextState === "function" ? (nextState as (prevState: T) => T)(state) : nextState; setState(value); setIsValid(validationFunc(value)); }, [validationFunc, state] ); return [state, onChange, isValid]; }