Created
April 11, 2023 10:16
-
-
Save tjinlag/904958812b0b50f39563f629c62524d3 to your computer and use it in GitHub Desktop.
React Custom Hook: useStateWithValidation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useCallback } from "react" | |
export default function useStateWithValidation(validationFunc, initialValue) { | |
const [state, setState] = useState(initialValue) | |
const [isValid, setIsValid] = useState(() => validationFunc(state)) | |
const onChange = useCallback( | |
nextState => { | |
const value = | |
typeof nextState === "function" ? nextState(state) : nextState | |
setState(value) | |
setIsValid(validationFunc(value)) | |
}, | |
[validationFunc] | |
) | |
return [state, onChange, isValid] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment