DEV Community

Cover image for React Custom Hook: useStateWithValidation
Sergey Leschev
Sergey Leschev

Posted on

React Custom Hook: useStateWithValidation

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useStateWithValidation" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks

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]
}
Enter fullscreen mode Exit fullscreen mode

The useStateWithValidation hook combines the useState and useCallback hooks from React to provide an elegant solution. It takes two parameters: a validation function and an initial value. The validation function determines whether the current state is considered valid or not.

One of the key advantages of this custom hook is its flexibility. You can pass any validation function that suits your specific requirements. Whether it's checking the length of a string, ensuring a numeric value falls within a certain range, or performing more complex validations, useStateWithValidation has got you covered.

import useStateWithValidation from "./useStateWithValidation"

export default function StateWithValidationComponent() {
    const [username, setUsername, isValid] = useStateWithValidation(
        name => name.length > 5,
        ""
    )
    return (
        <>
            <div>Valid: {isValid.toString()}</div>
            <input
                type="text"
                value={username}
                onChange={e => setUsername(e.target.value)}
            />
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

In this example, the StateWithValidationComponent uses the useStateWithValidation hook to manage the username state. The validation function checks if the length of the username is greater than 5 characters, and the isValid variable reflects the validity of the current input.

Full Version | React Custom Hooks:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4

Top comments (1)

Collapse
 
scriptkavi profile image
ScriptKavi

Why create one when you can get all awesome hooks in a single library?

Try scriptkavi/hooks. Copy paste style and easy to integrate with its own CLI