{"id":14275,"url":"\/distributions\/14275\/click?bit=1&hash=bccbaeb320d3784aa2d1badbee38ca8d11406e8938daaca7e74be177682eb28b","title":"\u041d\u0430 \u0447\u0451\u043c \u0437\u0430\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u044e\u0442 \u043f\u0440\u043e\u0444\u0435\u0441\u0441\u0438\u043e\u043d\u0430\u043b\u044c\u043d\u044b\u0435 \u043f\u0440\u043e\u0434\u0430\u0432\u0446\u044b \u0430\u0432\u0442\u043e?","buttonText":"\u0423\u0437\u043d\u0430\u0442\u044c","imageUuid":"f72066c6-8459-501b-aea6-770cd3ac60a6"}

React Custom Hook: useStateWithValidation

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.

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.

0
Комментарии
-3 комментариев
Раскрывать всегда