Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Created April 11, 2023 10:16
Show Gist options
  • Save tjinlag/904958812b0b50f39563f629c62524d3 to your computer and use it in GitHub Desktop.
Save tjinlag/904958812b0b50f39563f629c62524d3 to your computer and use it in GitHub Desktop.
React Custom Hook: useStateWithValidation
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