{"id":7308,"date":"2021-09-12T18:45:23","date_gmt":"2021-09-12T16:45:23","guid":{"rendered":"http:\/\/www.unimedia.tech.mialias.net\/a-quick-introduction-to-react-hooks\/"},"modified":"2023-12-18T13:07:55","modified_gmt":"2023-12-18T12:07:55","slug":"a-quick-introduction-to-react-hooks","status":"publish","type":"post","link":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/","title":{"rendered":"A Quick Introduction to React Hooks"},"content":{"rendered":"\n<p>In this article, we will briefly learn what React Hooks are, the types of hooks, and also basic examples of using some of these hooks in your <a href=\"https:\/\/www.unimedia.tech\/de\/category\/technical-guides-de\/react-technical-guides-de\/\">React app<\/a>.<\/p>\n\n\n\n<p>You may also be interested in: <a href=\"https:\/\/www.unimedia.tech\/2021\/08\/17\/stripe-checkout-integration-with-react\/\">&#8220;Stripe Checkout Integration with React&#8221;<\/a><\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What Are React Hooks?<\/h2>\n\n\n\n<p>React Hooks are built-in functions that allow you to use state within function components. Introduced as special APIs in the React 16.8 version released in 2019, Hooks will allow you to \u2018hook into\u2019 React features such as lifecycle methods. A feat that was previously only possible using class components.&nbsp;<\/p>\n\n\n\n<p>React Hooks are incredibly powerful because they allow React <a href=\"https:\/\/www.unimedia.tech\/de\/bespoke-software-development\/\">developers <\/a>to transform stateless functional components from just rendering reusable UIs to being capable of saving and maintaining state and logic. Before that, <a href=\"https:\/\/www.unimedia.tech\/de\/engagierte-entwicklungsteams\/\">developers <\/a>found it hard to reuse logic and share state between class components without using even more complex react abstractions. React Hooks made it possible to extract both stateful logic between components.&nbsp;<\/p>\n\n\n\n<p>In summary, here are benefits that developers gained from the introduction of React Hooks.&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>More straightforward code structure that does away with the \u2018<strong>this and binds\u2019 <\/strong>keywords.<\/li><\/ul>\n\n\n\n<ul class=\"wp-block-list\"><li>Easier to reuse logic and share state without dealing with complex React abstractions that are hard to test and manage.<\/li><li>A more precise top-down one-way data flow is possible without disrupting your existing components\u2019 order.&nbsp;<\/li><li>When optimally used, React Hooks can help you do away with the need to integrate a state management library.<\/li><\/ul>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common React Hooks<\/h2>\n\n\n\n<p>There are various types of in-built react hooks. You can even create your own Custom Hooks containing your own desired functional logic, which you can reuse across different components.&nbsp;<\/p>\n\n\n\n<p><a href=\"https:\/\/reactjs.org\/blog\/2019\/02\/06\/react-v16.8.0.html\">The React 16.8 release<\/a> came with ten built-in hooks categorized into two:&nbsp; Basic Hooks and Additional Hooks. Of these hooks, we will examine two hooks that are the most commonly used: useState and useEffect.&nbsp;&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">UseState React Hook<\/h3>\n\n\n\n<p>The useState Hook is the most popular React hook. It allows you to \u2018use state\u2019 in a function component. This means you can read, manipulate and update state using the useState Hook.&nbsp;<\/p>\n\n\n\n<p>A basic rendition of the useState Hook is shown below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const &#91;state, setState] = useState(initialState);<\/code><\/pre>\n\n\n\n<p>For example, the sample above has a <em>state<\/em> which is initially the same value as <em>initialState. <\/em>The<em> initialState <\/em>can take a number, string, or even an array depending on the data type at hand.<em> setState <\/em>is a function that\u2019s used to update the state value. E.g. setState(updatedState).&nbsp;&nbsp;<\/p>\n\n\n\n<p>Let\u2019s use the useState Hook in a simple, functional component.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Age() {\n const &#91;age, setAge] = useState(10);\n \n return (\n     &lt;div&gt;\n         &lt;p&gt;I am {age} Years Old&lt;\/p&gt;\n       &lt;div&gt;\n          &lt;button onClick={() =&gt; setAge(age + 1)}&gt;Increase my age!      &lt;\/button&gt;\n          &lt;button onClick={() =&gt; setAge(age - 1)}&gt;Decrease my age! &lt;\/button&gt;\n       &lt;\/div&gt;\n     &lt;\/div&gt;\n )\n}<\/code><\/pre>\n\n\n\n<p>Let\u2019s quickly explain how the above code works:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>We have the basic rendition of the hook:<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>    const &#91;age, setAge] = useState(10);<\/code><\/pre>\n\n\n\n<p><em>age<\/em> has an initial state of 10 which we then call between the &lt;p&gt; tag.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The buttons have an onClick handler which calls the <em>setAge<\/em> function, which will increase and or decrease our initial <em>age <\/em>state depending on the button clicked.&nbsp;<\/li><\/ul>\n\n\n\n<p><img decoding=\"async\" src=\"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/k-mbbwn48r5oW3kMBQ7ZDaiXg1JQJv1fZSUxVW6I3fUtvDNWkxAO6s3wSWl_ssJLcDe8kgH-ew-bR7nASc0a4yl6OV_XBXbA1r4DpaAQFttKgidwr7iy_LNn0-h-XQWdSUT83w0ls0.gif\" style=\"width: 1024px\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">UseEffect React Hook<\/h3>\n\n\n\n<p>The useEffect Hook accepts a function that it runs after each render. It\u2019s commonly used for performing side effects. This can range from manipulating the DOM or Browser APIs or even fetching data from external APIs. The useEffect hook also helps us achieve capabilities in a function component previously done by React lifecycle methods. Think of the useEffect Hook as the combination of the <em>componentDidMount<\/em>, <em>componentDidUpdate<\/em>, and <em>componentWillUnmount<\/em> <a href=\"https:\/\/reactjs.org\/docs\/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class\">lifecycle methods<\/a>. Besides, we can also set the useEffect hook to render based on specific value changes.<\/p>\n\n\n\n<p>Here\u2019s a basic rendition of the useEffect Hook.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>useEffect(functionToRun);<\/code><\/pre>\n\n\n\n<p>For example, let\u2019s use the useEffect Hook more elaboratively using the previous functional component sample.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Age() {\n const &#91;age, setAge] = useState(10);\n \n useEffect(() =&gt; {\n   setAge(20)\n },&#91;]);\n \n return (\n   &lt;div&gt;\n     &lt;p&gt;I am {age} Years Old&lt;\/p&gt;\n     &lt;div&gt;\n       &lt;button onClick={() =&gt; setAge(age + 1)}&gt;\n         Increase my age!\n       &lt;\/button&gt;\n       &lt;button onClick={() =&gt; setAge(age - 1)}&gt;\n         Decrease my age!\n       &lt;\/button&gt;\n     &lt;\/div&gt;\n   &lt;\/div&gt;\n );\n}<\/code><\/pre>\n\n\n\n<p>The useEffect at render sets the new <em>age<\/em> value to 20. We also passed an empty array which will let the useEffect hook run once only.<\/p>\n\n\n\n<p><img decoding=\"async\" src=\"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/NIyYbkV8J0wmyo4kzsQ_6j7rxSUwyI46i1l3xDgF8kIeafeVLxd2XN_7PMh41vpWa-u5Y1DbCuJTVUhHBWlfnrcBNn5SiQcNLO53JGfd-1soB_ZPGzQxqx1RK__uwa2WGXDvdil6s0.gif\" style=\"width: 1024px\"><\/p>\n\n\n\n<p>I\u2019ve placed a <em>console.log<\/em> in the display above. We can see how the value of <em>age <\/em>state changed from the initial 10 to 20, caused by the useEffect hook. We then see how the state changes as we click the button.&nbsp;&nbsp;<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Other React Hooks<\/h3>\n\n\n\n<p>There are also other Hooks such as useContext(), useMemo(), amongst others. You can have a look at the rest in the <a href=\"https:\/\/reactjs.org\/docs\/hooks-reference.html\">official documentation<\/a>.<\/p>\n\n\n\n<p>There are, however, two rules you should follow when using React Hooks.&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Always call hooks at the top level, as shown in the examples we\u2019ve used. This means that we can\u2019t call hooks inside loops, conditions, or nested functions.<\/li><li>Only use Hooks from inside React function components.<\/li><\/ul>\n\n\n\n<p>Many Code IDEs like VSCode have an inbuilt linter that enforces these rules and more.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Users App<\/h2>\n\n\n\n<p>Finally, let\u2019s create a more complex app using all we\u2019ve learned about React, useState, and useEffect Hooks.&nbsp;<\/p>\n\n\n\n<p>We will be fetching data from an <a href=\"https:\/\/jsonplaceholder.typicode.com\/\">external API with fake users data<\/a>. As we\u2019ve learned, this is a perfect use case for the useEffect Hook.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Users(){\n const &#91;users, setUsers] = useState(&#91;]);\n useEffect(() =&gt; {\n       fetch(\"https:\/\/jsonplaceholder.typicode.com\/users\/\")\n           .then(res =&gt; res.json())\n           .then(data =&gt; setUsers(data))\n     }, &#91;])\n \n return (\n     &lt;ul&gt;\n         {users.map(user =&gt; (\n         &lt;li key={user.id}&gt;\n             {user.name}lives in {user.address.city}\n         &lt;\/li&gt;\n         ))}\n     &lt;\/ul&gt;\n );\n}<\/code><\/pre>\n\n\n\n<p>In the sample above, you can see how we\u2019ve used:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The useState hook to set and update state including inside the useEffect Hook.<\/li><li>The useEffect hook interacts with the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Fetch_API\">Browser API called Fetch<\/a>, which allows us to cull data from external APIs. We also passed an empty array to make sure it ran once.<\/li><\/ul>\n\n\n\n<figure class=\"wp-block-video\"><video controls src=\"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2021\/09\/Users_Reactapp_with_Hooks.mp4\"><\/video><\/figure>\n\n\n\n<p>Again in the video above, I\u2019ve placed a <em>console.log<\/em> so you can see how we pulled out specific data to display.&nbsp;<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<p>We had fun! React Hooks are really powerful when used correctly. In conclusion, we learned what React Hooks are and the immense benefits they bring to developers. In addition, we also briefly examined the various types of hooks and the rules guiding their usage. Lastly, we created a simple React app that demonstrated how to use the useState and useEffect hooks.<\/p>\n\n\n\n<p>If you\u2019re feeling adventurous and want to build more apps with React hooks, check out our <a href=\"https:\/\/www.unimedia.tech\/2021\/08\/17\/stripe-checkout-integration-with-react\/\">Stripe Checkout Integration with React<\/a> article.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Unimedia Technology<\/h2>\n\n\n\n<p>Here at <a href=\"https:\/\/www.unimedia.tech\/de\/\">Unimedia Technology<\/a> we have a team of<strong> React Developers<\/strong> that can help you develop your most complex react Applications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>React Hooks are inbuilt React functions that allow developers to manage state and perform logical actions in a React function component.<\/p>\n","protected":false},"author":6,"featured_media":6661,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[214,219],"tags":[],"class_list":["post-7308","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react-technical-guides-de","category-technical-guides-de"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v21.6 (Yoast SEO v27.1.1) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>A Quick Introduction to React Hooks - Unimedia Technology<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/\" \/>\n<meta property=\"og:locale\" content=\"de_DE\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"A Quick Introduction to React Hooks\" \/>\n<meta property=\"og:description\" content=\"React Hooks are inbuilt React functions that allow developers to manage state and perform logical actions in a React function component.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/\" \/>\n<meta property=\"og:site_name\" content=\"Unimedia Technology\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.linkedin.com\/company\/unimedia-technology\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-09-12T16:45:23+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-12-18T12:07:55+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/4-1-4.png\" \/>\n\t<meta property=\"og:image:width\" content=\"700\" \/>\n\t<meta property=\"og:image:height\" content=\"400\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Unimedia\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@UnimediaCTO\" \/>\n<meta name=\"twitter:site\" content=\"@UnimediaCTO\" \/>\n<meta name=\"twitter:label1\" content=\"Verfasst von\" \/>\n\t<meta name=\"twitter:data1\" content=\"Unimedia\" \/>\n\t<meta name=\"twitter:label2\" content=\"Gesch\u00e4tzte Lesezeit\" \/>\n\t<meta name=\"twitter:data2\" content=\"6\u00a0Minuten\" \/>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"A Quick Introduction to React Hooks - Unimedia Technology","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/","og_locale":"de_DE","og_type":"article","og_title":"A Quick Introduction to React Hooks","og_description":"React Hooks are inbuilt React functions that allow developers to manage state and perform logical actions in a React function component.","og_url":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/","og_site_name":"Unimedia Technology","article_publisher":"https:\/\/www.linkedin.com\/company\/unimedia-technology\/","article_published_time":"2021-09-12T16:45:23+00:00","article_modified_time":"2023-12-18T12:07:55+00:00","og_image":[{"width":700,"height":400,"url":"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/4-1-4.png","type":"image\/png"}],"author":"Unimedia","twitter_card":"summary_large_image","twitter_creator":"@UnimediaCTO","twitter_site":"@UnimediaCTO","twitter_misc":{"Verfasst von":"Unimedia","Gesch\u00e4tzte Lesezeit":"6\u00a0Minuten"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/#article","isPartOf":{"@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/"},"author":{"name":"Unimedia","@id":"https:\/\/www.unimedia.tech\/de\/#\/schema\/person\/3a250aa22526d5c9ff6bc95bb380a5dd"},"headline":"A Quick Introduction to React Hooks","datePublished":"2021-09-12T16:45:23+00:00","dateModified":"2023-12-18T12:07:55+00:00","mainEntityOfPage":{"@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/"},"wordCount":994,"publisher":{"@id":"https:\/\/www.unimedia.tech\/de\/#organization"},"image":{"@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/#primaryimage"},"thumbnailUrl":"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/4-1-4.png","articleSection":["React","Technical Guides"],"inLanguage":"de"},{"@type":"WebPage","@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/","url":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/","name":"A Quick Introduction to React Hooks - Unimedia Technology","isPartOf":{"@id":"https:\/\/www.unimedia.tech\/de\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/#primaryimage"},"image":{"@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/#primaryimage"},"thumbnailUrl":"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/4-1-4.png","datePublished":"2021-09-12T16:45:23+00:00","dateModified":"2023-12-18T12:07:55+00:00","breadcrumb":{"@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/#breadcrumb"},"inLanguage":"de","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/"]}]},{"@type":"ImageObject","inLanguage":"de","@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/#primaryimage","url":"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/4-1-4.png","contentUrl":"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/4-1-4.png","width":700,"height":400,"caption":"react unimedia"},{"@type":"BreadcrumbList","@id":"https:\/\/www.unimedia.tech\/de\/a-quick-introduction-to-react-hooks\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.unimedia.tech\/de\/"},{"@type":"ListItem","position":2,"name":"A Quick Introduction to React Hooks"}]},{"@type":"WebSite","@id":"https:\/\/www.unimedia.tech\/de\/#website","url":"https:\/\/www.unimedia.tech\/de\/","name":"Unimedia Technology","description":"Your software development partner","publisher":{"@id":"https:\/\/www.unimedia.tech\/de\/#organization"},"alternateName":"Unimedia Tech","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.unimedia.tech\/de\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"de"},{"@type":"Organization","@id":"https:\/\/www.unimedia.tech\/de\/#organization","name":"Unimedia Technology","alternateName":"Unimedia Tech","url":"https:\/\/www.unimedia.tech\/de\/","logo":{"@type":"ImageObject","inLanguage":"de","@id":"https:\/\/www.unimedia.tech\/de\/#\/schema\/logo\/image\/","url":"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/cloud_border-3.png","contentUrl":"https:\/\/www.unimedia.tech\/wp-content\/uploads\/2023\/12\/cloud_border-3.png","width":403,"height":309,"caption":"Unimedia Technology"},"image":{"@id":"https:\/\/www.unimedia.tech\/de\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.linkedin.com\/company\/unimedia-technology\/","https:\/\/x.com\/UnimediaCTO","https:\/\/www.instagram.com\/unimedia.technology\/"]},{"@type":"Person","@id":"https:\/\/www.unimedia.tech\/de\/#\/schema\/person\/3a250aa22526d5c9ff6bc95bb380a5dd","name":"Unimedia","image":{"@type":"ImageObject","inLanguage":"de","@id":"https:\/\/www.unimedia.tech\/de\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/5901fd1c4628e2b48ffd4e47324e8fe0751b39e556a167f078471d4c4bec0f6f?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/5901fd1c4628e2b48ffd4e47324e8fe0751b39e556a167f078471d4c4bec0f6f?s=96&d=mm&r=g","caption":"Unimedia"}}]}},"_links":{"self":[{"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/posts\/7308","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/comments?post=7308"}],"version-history":[{"count":0,"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/posts\/7308\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/media\/6661"}],"wp:attachment":[{"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/media?parent=7308"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/categories?post=7308"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.unimedia.tech\/de\/wp-json\/wp\/v2\/tags?post=7308"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}