{"id":351391,"date":"2024-05-20T12:46:03","date_gmt":"2024-05-20T12:46:03","guid":{"rendered":"http:\/\/savepearlharbor.com\/?p=351391"},"modified":"-0001-11-30T00:00:00","modified_gmt":"-0001-11-29T21:00:00","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=351391","title":{"rendered":"<span>React Custom Hook: useStateWithValidation<\/span>"},"content":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p>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 &#171;useStateWithValidation&#187; hook, one of the many carefully crafted hooks available in the collection of React custom hooks.<\/p>\n<p>Github:\u00a0<a href=\"https:\/\/github.com\/sergeyleschev\/react-custom-hooks\" rel=\"noopener noreferrer nofollow\"><u>https:\/\/github.com\/sergeyleschev\/react-custom-hooks<\/u><\/a><\/p>\n<pre><code class=\"javascript\">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] }<\/code><\/pre>\n<p>The <strong>useStateWithValidation<\/strong> 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.<\/p>\n<p>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&#8217;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.<\/p>\n<pre><code class=\"javascript\">import useStateWithValidation from \".\/useStateWithValidation\"  export default function StateWithValidationComponent() {     const [username, setUsername, isValid] = useStateWithValidation(         name => name.length > 5,         \"\"     )     return (         &lt;>             &lt;div>Valid: {isValid.toString()}&lt;\/div>             &lt;input                 type=\"text\"                 value={username}                 onChange={e => setUsername(e.target.value)}             \/>         &lt;\/>     ) }<\/code><\/pre>\n<p>In this example, the StateWithValidationComponent uses the <em>useStateWithValidation<\/em> 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.<\/p>\n<p>Full Version | React Custom Hooks: <a href=\"https:\/\/habr.com\/en\/articles\/746760\/\" rel=\"noopener noreferrer nofollow\">https:\/\/habr.com\/en\/articles\/746760\/<\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/752828\/\"> https:\/\/habr.com\/ru\/articles\/752828\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p>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 &#171;useStateWithValidation&#187; hook, one of the many carefully crafted hooks available in the collection of React custom hooks.<\/p>\n<p>Github:\u00a0<a href=\"https:\/\/github.com\/sergeyleschev\/react-custom-hooks\" rel=\"noopener noreferrer nofollow\"><u>https:\/\/github.com\/sergeyleschev\/react-custom-hooks<\/u><\/a><\/p>\n<pre><code class=\"javascript\">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] }<\/code><\/pre>\n<p>The <strong>useStateWithValidation<\/strong> 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.<\/p>\n<p>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&#8217;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.<\/p>\n<pre><code class=\"javascript\">import useStateWithValidation from \".\/useStateWithValidation\"  export default function StateWithValidationComponent() {     const [username, setUsername, isValid] = useStateWithValidation(         name => name.length > 5,         \"\"     )     return (         &lt;>             &lt;div>Valid: {isValid.toString()}&lt;\/div>             &lt;input                 type=\"text\"                 value={username}                 onChange={e => setUsername(e.target.value)}             \/>         &lt;\/>     ) }<\/code><\/pre>\n<p>In this example, the StateWithValidationComponent uses the <em>useStateWithValidation<\/em> 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.<\/p>\n<p>Full Version | React Custom Hooks: <a href=\"https:\/\/habr.com\/en\/articles\/746760\/\" rel=\"noopener noreferrer nofollow\">https:\/\/habr.com\/en\/articles\/746760\/<\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/752828\/\"> https:\/\/habr.com\/ru\/articles\/752828\/<\/a><br \/><\/br><\/br><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-351391","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/351391","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=351391"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/351391\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=351391"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=351391"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=351391"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}