<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" > <channel> <title>Reactjs Archives - CopyCat Blog</title> <atom:link href="https://www.copycat.dev/blog/tag/reactjs/feed/" rel="self" type="application/rss+xml" /> <link>https://www.copycat.dev/blog/tag/reactjs/</link> <description>Perfect the art of copying code</description> <lastBuildDate>Wed, 15 Feb 2023 10:54:35 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod> hourly </sy:updatePeriod> <sy:updateFrequency> 1 </sy:updateFrequency> <generator>https://wordpress.org/?v=6.7.1</generator> <image> <url>https://www.copycat.dev/blog/wp-content/uploads/2022/04/cropped-cat-4x-32x32.png</url> <title>Reactjs Archives - CopyCat Blog</title> <link>https://www.copycat.dev/blog/tag/reactjs/</link> <width>32</width> <height>32</height> </image> <site xmlns="com-wordpress:feed-additions:1">213178576</site> <item> <title>Guide to building your ReactJS custom hooks</title> <link>https://www.copycat.dev/blog/react-custom-hooks/?utm_source=rss&utm_medium=rss&utm_campaign=react-custom-hooks</link> <comments>https://www.copycat.dev/blog/react-custom-hooks/#respond</comments> <dc:creator><![CDATA[Emmanuel Uchenna]]></dc:creator> <pubDate>Sat, 13 Aug 2022 04:58:08 +0000</pubDate> <category><![CDATA[React.js]]></category> <category><![CDATA[Custom Hooks]]></category> <category><![CDATA[How To]]></category> <category><![CDATA[React Guide]]></category> <category><![CDATA[react.js]]></category> <category><![CDATA[Reactjs]]></category> <guid isPermaLink="false">https://www.copycat.dev/blog/?p=715</guid> <description><![CDATA[<p>Table of Contents Introducing the concept of React custom hooksWhat is a custom hook in ReactWhy you need to use custom Hooks in ReactWhy and when to use React Custom HooksRules of Custom React hookGetting started with your React appSetup your development environmentCreating your custom HooksExample: useFetch custom hookExample: useToggle custom hookExample: useRequireAuth custom hookExample: useCopyToClipboard custom hookExample: useDeviceDetect custom hookExample: useEffect hookExample: useState hookConclusionFurther readingsVideos examplesAbout CopycatIntroducing the […]</p> <p>The post <a rel="nofollow" href="https://www.copycat.dev/blog/react-custom-hooks/">Guide to building your ReactJS custom hooks</a> appeared first on <a rel="nofollow" href="https://www.copycat.dev/blog">CopyCat Blog</a>.</p> ]]></description> <content:encoded><![CDATA[<div class="convertful-189269"></div> <div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset2 animation-fade rtoc_open noto-sans" data-id="715" data-theme="CopyCat Theme"> <div id="rtoc-mokuji-title" class=" rtoc_left"> <button class="rtoc_open_close rtoc_open"></button> <span>Table of Contents</span> </div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">Introducing the concept of React custom hooks</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-2">What is a custom hook in React</a></li><li class="rtoc-item"><a href="#rtoc-3"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#why-you-need-to-use-custom-hooks-in-react"></a>Why you need to use custom Hooks in React</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-4"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#why-and-when-to-use-react-custom-hooks"></a>Why and when to use React Custom Hooks</a></li><li class="rtoc-item"><a href="#rtoc-5"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#rules-of-custom-react-hook"></a>Rules of Custom React hook</a></li><li class="rtoc-item"><a href="#rtoc-6"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#getting-started-with-your-react-app"></a>Getting started with your React app</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-7"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#setup-your-development-environment"></a>Setup your development environment</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-8"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#creating-your-custom-hooks"></a>Creating your custom Hooks</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-9"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example--usefetch-custom-hook"></a>Example: <code>useFetch</code> custom hook</a></li><li class="rtoc-item"><a href="#rtoc-10">Example: <code>useToggle</code> custom hook</a></li><li class="rtoc-item"><a href="#rtoc-11">Example: <code>useRequireAuth</code> custom hook</a></li><li class="rtoc-item"><a href="#rtoc-12"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example--usecopytoclipboard-custom-hook"></a>Example: <code>useCopyToClipboard</code> custom hook</a></li><li class="rtoc-item"><a href="#rtoc-13"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example--usedevicedetect-custom-hook"></a>Example: <code>useDeviceDetect</code> custom hook</a></li><li class="rtoc-item"><a href="#rtoc-14"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example-useeffect-hook"></a>Example: <code>useEffect</code> hook</a></li><li class="rtoc-item"><a href="#rtoc-15"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example-usestate-hook"></a>Example: <code>useState</code> hook</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-16"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#conclusion"></a>Conclusion</a></li><li class="rtoc-item"><a href="#rtoc-17"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#further-readings"></a>Further readings</a></li><li class="rtoc-item"><a href="#rtoc-18"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#videos-examples"></a>Videos examples</a></li><li class="rtoc-item"><a href="#rtoc-19"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#about-copycat"></a>About Copycat</a></li></ol></div><h2 id="rtoc-1" class="wp-block-heading">Introducing the concept of React custom hooks</h2> <p>ReactJS has introduced powerful improvements to web development since its introduction in 2013 as part of the family of UI libraries. <a href="https://www.peerbits.com/blog/reasons-to-choose-reactjs-for-your-web-development-project.html">This improvement</a> is not only thanks to the introduction of custom hooks, but also amongst others. These improvements are evident in the speed of development of web applications and the efficiency of the web applications.</p> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/183038325-f20d1221-778d-4896-8ace-29ba49917b5c.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/183038325-f20d1221-778d-4896-8ace-29ba49917b5c.png" alt="featured image"/></a></figure> <p>React also is the most popular web framework, according to the <a href="https://insights.stackoverflow.com/survey/2019#technology-_-most-loved-dreaded-and-wanted-web-frameworks">most recent Stack Overflow study</a>, while Angular came in ninth.</p> <p>React custom hooks are reusable functions that support the principles of ReactJS as identified above—support for reusable components, which are the building blocks of a React application. Hooks were also a new addition to ReactJS in <a href="https://reactjs.org/docs/hooks-custom.html">v16.8</a>.</p> <h3 id="rtoc-2" class="wp-block-heading">What is a custom hook in React</h3> <p>React hooks and React custom hooks let you use state and other React features without writing a class in your <a href="https://www.copycat.dev/blog/reactjs-components/">React component</a>. A custom Hook is a JavaScript function whose name starts with <code>use</code> and that may call other Hooks. The reason why custom hooks must start with the <code>use</code> keyword, is so that you can tell at a glance that <a href="https://reactjs.org/docs/hooks-rules.html">the rules of Hooks</a> apply to it.</p> <p>React custom hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), still every time you use a custom Hook, all state and effects inside of it are fully isolated.</p> <h3 id="rtoc-3" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#why-you-need-to-use-custom-hooks-in-react"></a>Why you need to use custom Hooks in React</h3> <ul class="wp-block-list"> <li>Custom React hooks enable you to remove unnecessary duplicated logic across your <a href="https://www.copycat.dev/blog/reactjs-components/">React components</a></li> <li>Custom Hooks offer the <strong>flexibility</strong> of sharing logic that were not possible in <a href="https://www.copycat.dev/blog/reactjs-components/">React components</a> before.</li> <li><strong>Reusability</strong> — The same hook can be used repeatedly without having to write twice.</li> <li><strong>Maintainability</strong> — Simpler to keep up. The logic of the hook only needs to be altered once, if at all.</li> <li><strong>Great Community</strong> — The likelihood is that the hook you’re considering has already been developed by someone. There are a ton of Custom Hooks on the web! You can locate one that fits your needs, utilize it as is, or even better, use it as a springboard to create something great!</li> <li><strong>Clean Code</strong> — A cleaner codebase will result from extracting all component logic into a hook.</li> </ul> <h2 id="rtoc-4" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#why-and-when-to-use-react-custom-hooks"></a>Why and when to use React Custom Hooks</h2> <p>As stated earlier, we use React Hooks because since its introduction, quite a while ago, Hooks gave function components the ability to use state and side-effects with built-in Hooks such as React’s useState Hook and React’s useEffect Hook.</p> <p>React only comes with a few number of built-in hooks, including useReducer, useCallback, useMemo, useContext, useState, and useEffect. However, React developers can design their own react custom hooks, known as custom hooks, by using existing Hooks as a foundation. In this tutorial, I will walk you through how to create a custom hook.</p> <h2 id="rtoc-5" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#rules-of-custom-react-hook"></a>Rules of Custom React hook</h2> <ul class="wp-block-list"> <li>Custom Hooks must have the prefix <code>use</code> in their namings. A unique hook might be called <code>useFetch</code> or <code>useDate</code>, for instance. In this tutorial, you will be walked through the nitty-gritty of creating a custom hook, one of such is the <code>useFetch</code> custom hook.</li> <li>Custom Hooks consist of built-in React Hooks or other custom Hooks. This entails that, a custom Hook is always a new composition of one or more Hooks. If a custom Hook does not use any hook internally, it is not a custom Hook and should not have the prefix <code>use</code>.</li> <li>The reason why you must start your Custom React hook with the prefix <code>use</code> is that it enables linters to quickly spot bugs, such as scenarios where usage goes against the rules of Hooks.</li> <li>You should only call Hooks at the top level. Hooks <strong>should not be called inside loops, conditions, or nested functions.</strong> Hooks should be used at the top level of your React function, before any early returns.</li> <li>Only call Hooks from React function components. Hooks should not be called from regular JavaScript functions. If you are wondering why these rules exist, it is because React uses the order that Hooks are invoked to associate each Hook with a certain local state. Placing a Hook inside of a condition can alter this order, preventing the subsequent Hooks from being called and, most likely, leading to bugs.</li> </ul> <h2 id="rtoc-6" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#getting-started-with-your-react-app"></a>Getting started with your React app</h2> <p>In this tutorial, you will be creating a React app using <a href="https://create-react-app.dev/">CRA</a>.</p> <h3 id="rtoc-7" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#setup-your-development-environment"></a>Setup your development environment</h3> <p>You will scaffold a new React project. In this tutorial, I refer to my React app as <code>custom-hook-tutorial</code>. In your terminal, type the following:</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> npx create-react-app custom-hook-tutorial </pre></div> <p>After having created your app and all dependencies automatically installed, you will need to navigate into the project directory and run the app. For that, run the following command in your terminal:</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> cd custom-hook-tutorial && npm start </pre></div> <p>You should see similar output below in your terminal:</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> $ npm start > custom-hook-tutorial@0.1.0 start > react-scripts start </pre></div> <p>Your React app will then start hot reloading your development environment and your app should be running on <code>localhost:3000</code> by default.</p> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/176993096-b0464d20-5db0-4da2-b67a-cef27bbcaa3e.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/176993096-b0464d20-5db0-4da2-b67a-cef27bbcaa3e.png" alt="image of React app"/></a></figure> <h2 id="rtoc-8" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#creating-your-custom-hooks"></a>Creating your custom Hooks</h2> <p>In this tutorial, I shall walk you through how to create your custom hooks which include <code>useFetch</code>, <code>useToggle</code>, <code>useRequireAuth</code>, <code>useCopyToClipboard</code>, and <code>useDeviceDetect</code> custom hooks. Let’s get started!</p> <figure class="wp-block-image"><a href="https://camo.githubusercontent.com/caba8971fbed04d39180d31807cdb77a0b86c8a382848186ced14534bc1d2c08/68747470733a2f2f632e74656e6f722e636f6d2f723358647650734156336b41414141532f64657370696361626c652d6d652d6d696e696f6e732e676966" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://camo.githubusercontent.com/caba8971fbed04d39180d31807cdb77a0b86c8a382848186ced14534bc1d2c08/68747470733a2f2f632e74656e6f722e636f6d2f723358647650734156336b41414141532f64657370696361626c652d6d652d6d696e696f6e732e676966" alt="Let's get started"/></a></figure> <p>In every React project, I like to have my own <code>useFetch</code> custom hook. In your <code>src</code> folder, create a new folder called <code>hooks</code>. This folder shall contain all your custom hooks.</p> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/182544670-2b69fab1-bbd3-4c18-acc4-792064b50a15.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/182544670-2b69fab1-bbd3-4c18-acc4-792064b50a15.png" alt="folder structure image"/></a></figure> <h3 id="rtoc-9" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example--usefetch-custom-hook"></a>Example: <code>useFetch</code> custom hook</h3> <p>The <code>useFetch</code> custom hook is used to fetch data from an API. You will build it to return <code>isPending</code>, <code>error</code>, and the <code>data</code>.</p> <p>Inside your <code>hooks</code> folder, create a file and name it <code>useFetch.js</code> and paste this code below. We must use the prefix <code>use</code> as earlier discussed earlier.</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> // useFetch.js import React from "react"; import { useState, useEffect } from 'react'; export const useFetch = (url, fakeData = "") => { const [isPending, setIsPending] = useState(true); const [error, setError] = useState(null); const [data, setData] = useState(fakeData); useEffect(() => { const abortCont = new AbortController(); fetch(url, { signal: abortCont.signal, }) .then(res => { if (!res.ok) { throw Error("Could not connect to the server"); } return res.json(); }).then((data) => { setData(data); setIsPending(false); }).catch(err => { if (err.name === "AbortError") { setError(err.message); console.error("Fetch Aborted."); throw Error("Fetch Aborted."); } else { setError(err.message); throw Error("An error occurred while trying to fetch from the remote server."); } }); return () => abortCont.abort(); }, [url,]); return { isPending, error, data, }; }; // How to use const { isPending, error, data } = useFetch(URL, fakeData); if (error) { console.error(error); } </pre></div> <p>Let us go through our code and see how it works and what each piece does:</p> <p>1. You initialized the state of our app using React state hook (useState)</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> const [isPending, setIsPending] = useState(true); const [error, setError] = useState(null); const [data, setData] = useState(fakeData); </pre></div> <ul class="wp-block-list"> <li>You initialized <strong>isPending</strong> to <code>true</code></li> <li>You initialized <strong>error</strong> to <code>null</code></li> <li>You initialized <strong>data</strong> using a custom <code>fakeData</code></li> </ul> <p>2. You use the JavaScript <a href="https://www.copycat.dev/blog/react-fetch/">fetch API</a> to fetch data from a custom <code>url</code>. You then used the state; <code>setData</code> to persist the fetched data in your app’s state.</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> fetch(url, { signal: abortCont.signal, }) .then(res => { if (!res.ok) { throw Error("Could not connect to the server"); } return res.json(); }).then((data) => { setData(data); console.log(data); setIsPending(false); }).catch(err => { if (err.name === "AbortError") { setError(err.message); console.error("Fetch Aborted."); throw Error("Fetch Aborted."); } else { setError(err.message); throw Error("An error occurred while trying to fetch from the remote server."); } }); </pre></div> <ul class="wp-block-list"> <li>For an in-depth walk-through on how to fetch data from API using the fetch API, please refer to this <a href="https://www.copycat.dev/blog/react-fetch/">article</a>.</li> </ul> <p>3. You import react, then destructure the return object in other to use the result. Here, we are using console to log the data.</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import React from "react"; const { isPending, error, data } = useFetch(URL, fakeData); console.log(data); if (error) { console.error(error); } </pre></div> <h3 id="rtoc-10" class="wp-block-heading">Example: <code>useToggle</code> custom hook</h3> <p>The <code>useToggle</code> custom hook essentially toggles a parameter’s value from <code>true</code> to <code>false</code> by taking a parameter with one of those two values. It comes in handy when you wish to change one action into its opposite, such as when we want to reveal or conceal a modal, show more or less text, or open or close a side menu.</p> <p>Still inside your <code>hooks</code> folder, create a file and name it <code>useToggle.js</code> and paste this code below.</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import React from "react"; import { useCallback, useState } from 'react'; // Usage export default function App() { const [isTextChanged, setIsTextChanged] = useToggle(); return ( <button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button> ); } // Parameter is the boolean, with default "false" value const useToggle = (initialState = false) => { // Initialize the state const [state, setState] = useState(initialState); // Define and memorize toggler function in case we pass down the component, // This function change the boolean value to it's opposite value const toggle = useCallback(() => setState(state => !state), []); return [state, toggle] } </pre></div> <h3 id="rtoc-11" class="wp-block-heading">Example: <code>useRequireAuth</code> custom hook</h3> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import React from "react"; import Dashboard from "./Dashboard.js"; import Loading from "./Loading.js"; import { useRequireAuth } from "./use-require-auth.js"; export default function DashboardPage(props) { const auth = useRequireAuth(); // If auth is null (still fetching data) // or false (logged out) // then show loading indicator. if (!auth) { return <Loading />; } return <Dashboard auth={auth} />; } // (use-require-auth.js) import React from "react"; import { useEffect } from "react"; import { useAuth } from "./use-auth.js"; import { useRouter } from "./use-router.js"; function useRequireAuth(redirectUrl = "/signup") { const auth = useAuth(); const router = useRouter(); // If auth.user is false that means we're not // logged in and should redirect. useEffect(() => { if (auth.user === false) { router.push(redirectUrl); } }, [auth, router]); return auth; } </pre></div> <p>Adapted from <a href="https://usehooks.com/">https://usehooks.com/</a></p> <h3 id="rtoc-12" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example--usecopytoclipboard-custom-hook"></a>Example: <code>useCopyToClipboard</code> custom hook</h3> <p>The <code>useCopyToClipboard</code> custom hook allows you to copy the contents of the text to clipboard.</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import React from "react"; const useCopyToClipboard = text => { const copyToClipboard = str => { const el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); const success = document.execCommand('copy'); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } return success; }; const [copied, setCopied] = React.useState(false); const copy = React.useCallback(() => { if (!copied) setCopied(copyToClipboard(text)); }, [text]); React.useEffect(() => () => setCopied(false), [text]); return [copied, copy]; }; </pre></div> <p>Let us go through our code and see how it works and what each piece does:</p> <ol class="wp-block-list"> <li>You used the <code>useState()</code> hook to initialize the <code>copied</code> variable.</li> <li>You used the <code>useCallback()</code> hook to create a callback for the <code>copyToClipboard</code> method.</li> <li>You used the <code>useEffect()</code> hook to reset the <code>copied</code> state variable if the text changes.</li> <li>Finally, you returned the copied state variable and the <code>copy</code> callback.</li> </ol> <h3 id="rtoc-13" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example--usedevicedetect-custom-hook"></a>Example: <code>useDeviceDetect</code> custom hook</h3> <p>The <code>useDeviceDetect</code> custom hook essentially allows you to detect whether your users are on a mobile device or not.</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> // utils/useDeviceDetect.js import React from "react"; export default function useDeviceDetect() { const [isMobile, setMobile] = React.useState(false); React.useEffect(() => { const userAgent = typeof window.navigator === "undefined" ? "" : navigator.userAgent; const mobile = Boolean( userAgent.match( /Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i ) ); setMobile(mobile); }, []); return { isMobile }; } </pre></div> <p>Adapted from <a href="https://is.gd/LrBCi2">ThisCodeWorks</a></p> <h3 id="rtoc-14" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example-useeffect-hook"></a>Example: <code>useEffect</code> hook</h3> <p>The useState useEffect from React are hooks introduced in version 16.8. The <code>useEffect</code> Hook allows you to perform side effects in your <a href="https://www.copycat.dev/blog/reactjs-components/">React components</a>. This hook is the part of the foundation to build your custom hooks as seen above.</p> <p>Some examples of side effects are: <a href="https://www.copycat.dev/blog/react-fetch/">fetching data</a>, directly updating the DOM, and timers.</p> <p>useEffect accepts two arguments. The second argument is optional.</p> <p>useEffect(<code><function></code>, <code><dependency></code>)</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import React from "react"; import { useState, useEffect } from "react"; import ReactDOM from "react-dom/client"; export default function Counter() { const [count, setCount] = useState(0); const [calculation, setCalculation] = useState(0); useEffect(() => { setCalculation(() => count * 2); }, [count]); // <- add the count variable here return ( <> <p>Count: {count}</p> <button onClick={() => setCount((c) => c + 1)}>+</button> <p>Calculation: {calculation}</p> </> ); } </pre></div> <p>Adapted from <a href="https://www.w3schools.com/react/react_useeffect.asp">w3schools</a></p> <h3 id="rtoc-15" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#example-usestate-hook"></a>Example: <code>useState</code> hook</h3> <p>The useState useEffect from React are hooks introduced in version 16.8. The React <code>useState</code> Hook allows us to track state in a function component. This hook is the part of the foundation to build your custom hooks as seen above. For an in-dept guide on the useState hook, please see this <a href="https://www.copycat.dev/blog/react-usestate-hook%ef%bf%bc/">article</a>.</p> <p>State generally refers to data or properties that need to be tracking in an application.</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import React from "react"; import { useState } from "react"; import ReactDOM from "react-dom/client"; export default function Car() { const [car, setCar] = useState({ brand: "Ford", model: "Mustang", year: "1964", color: "red" }); return ( <> <h1>My {car.brand}</h1> <p> It is a {car.color} {car.model} from {car.year}. </p> </> ) } </pre></div> <p>Adapted from <a href="https://www.w3schools.com/react/react_usestate.asp">w3schools</a></p> <h2 id="rtoc-16" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#conclusion"></a>Conclusion</h2> <p>Almost all of the information you require about creating and using custom react hooks is covered in this article. You were walked through the nitty-gritty of creating a custom hook with real examples of custom hooks.</p> <p>We have shown how easy it is to create custom hooks and how many (open) sources are available for finding inspiration and using custom hooks that already exist (I attached more sources below).</p> <p>Try to spread this guide on the internet if you find it interesting.</p> <figure class="wp-block-image"><a href="https://camo.githubusercontent.com/5a790fcd2e122f2b67a2e86c3d535f529437c0924cea0ebb27fa3bef2a45b295/68747470733a2f2f632e74656e6f722e636f6d2f6b30486c774e5a57395a7341414141432f6b696e64657267617264656e2d636f6e67726174756c6174696f6e732e676966" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://camo.githubusercontent.com/5a790fcd2e122f2b67a2e86c3d535f529437c0924cea0ebb27fa3bef2a45b295/68747470733a2f2f632e74656e6f722e636f6d2f6b30486c774e5a57395a7341414141432f6b696e64657267617264656e2d636f6e67726174756c6174696f6e732e676966" alt="Congratulations"/></a></figure> <p>Thinking of learning more? Find below some links to further tutorials:</p> <h2 id="rtoc-17" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#further-readings"></a>Further readings</h2> <ol class="wp-block-list"> <li><a href="https://is.gd/iNp7yK">Beautiful hooks</a> – A curated list of hopefully <em>useful</em> React hooks</li> <li><a href="https://usehooks.com/">https://usehooks.com/</a> – Easy to understand React tutorials by ui.dev</li> <li><a href="https://is.gd/GzkTjx">How to Build Your Own Hooks: A Step-by-Step Guide</a> – freCodeCamp Blog</li> <li><a href="https://reactjs.org/docs/hooks-custom.html">React Documentation</a> — Custom Hooks</li> <li><a href="https://is.gd/KtuBj9">Awesome</a> — Amazing Repository that includes docs, videos, tutorial, and Awesome Custom Hooks.</li> </ol> <h2 id="rtoc-18" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#videos-examples"></a>Videos examples</h2> <figure class="wp-block-image"><a href="https://www.youtube.com/watch?v=Jl4q2cccwf0"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/182974026-d263f7c6-d03c-42ee-971e-efab97f26dc7.png" alt="Full React Tutorial #20 - YouTube"/></a></figure> <figure class="wp-block-image"><a href="https://www.youtube.com/watch?v=LlvBzyy-558"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/182980720-79394197-0b0b-4042-8f48-093fdc18f38d.png" alt="Hooks Course Explained - YouTube"/></a></figure> <h2 id="rtoc-19" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/d3d5dd9f7916da60fc7c093844653961#about-copycat"></a>About Copycat</h2> <p><a href="https://www.copycat.dev/">CopyCat</a> allows you to build UI faster. All you need to do is just copy production-ready code generated directly from Figma designs using AI. As a result, you can focus on building interactions, animations, networking, and everything else that will make you stand out. You can be an exceptional front-end developer who develops UI quickly using <a href="https://www.copycat.dev/">CopyCat</a>.</p> <div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-1 wp-block-buttons-is-layout-flex"> <div class="wp-block-button"><a class="wp-block-button__link has-background wp-element-button" href="https://www.copycat.dev/" style="background-color:#7b3beb">START BUILDING FASTER</a></div> </div> <p>The post <a rel="nofollow" href="https://www.copycat.dev/blog/react-custom-hooks/">Guide to building your ReactJS custom hooks</a> appeared first on <a rel="nofollow" href="https://www.copycat.dev/blog">CopyCat Blog</a>.</p> ]]></content:encoded> <wfw:commentRss>https://www.copycat.dev/blog/react-custom-hooks/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">715</post-id> </item> </channel> </rss>