Как стать автором
Обновить

React Custom Hook: useStateWithValidation

Уровень сложностиСредний
Время на прочтение2 мин
Количество просмотров1.6K

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]
}

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)}
            />
        </>
    )
}

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://habr.com/en/articles/746760/

Теги:
Хабы:
Всего голосов 2: ↑1 и ↓1+1
Комментарии0

Публикации

Истории

Работа

Ближайшие события

7 – 8 ноября
Конференция byteoilgas_conf 2024
МоскваОнлайн
7 – 8 ноября
Конференция «Матемаркетинг»
МоскваОнлайн
15 – 16 ноября
IT-конференция Merge Skolkovo
Москва
22 – 24 ноября
Хакатон «AgroCode Hack Genetics'24»
Онлайн
28 ноября
Конференция «TechRec: ITHR CAMPUS»
МоскваОнлайн
25 – 26 апреля
IT-конференция Merge Tatarstan 2025
Казань