<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ cheatsheet - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ cheatsheet - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 16:31:54 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/cheatsheet/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Vim Key Bindings – Vim Keys List Reference ]]>
                </title>
                <description>
                    <![CDATA[ Understanding Vim key bindings is crucial for navigating and editing text efficiently in Vim or Vim-based text editors like Neovim.  In this article, we'll explore the most common Vim key bindings that will help you navigate your text editor seamless... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/vim-key-bindings-reference/</link>
                <guid isPermaLink="false">66bb88320eaca026d8cfa5bd</guid>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ reference ]]>
                    </category>
                
                    <category>
                        <![CDATA[ vim ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sahil ]]>
                </dc:creator>
                <pubDate>Tue, 06 Feb 2024 09:28:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Neon-Green-Bold-Quote-Motivational-Tweet-Instagram-Post-4-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Understanding Vim key bindings is crucial for navigating and editing text efficiently in Vim or Vim-based text editors like Neovim. </p>
<p>In this article, we'll explore the most common Vim key bindings that will help you navigate your text editor seamlessly.</p>
<h2 id="heading-table-of-content">Table of Content</h2>
<ul>
<li><a class="post-section-overview" href="#heading-vim-modes">Vim Modes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-navigate-using-vim-key-bindings">How to Navigate using Vim Key Bindings</a></li>
<li><a class="post-section-overview" href="#heading-how-to-edit-text-in-normal-mode">How to Edit Text in Normal Mode</a></li>
<li><a class="post-section-overview" href="#heading-insert-mode">Insert Mode</a></li>
<li><a class="post-section-overview" href="#heading-visual-mode">Visual Mode</a></li>
<li><a class="post-section-overview" href="#heading-more-navigation-commands">More Navigation Commands</a></li>
<li><a class="post-section-overview" href="#heading-programming-specific-vim-key-bindings">Programming Specific Key Bindings</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-vim-modes">Vim Modes</h2>
<p>Vim operates in distinct modes, each designed for specific tasks:</p>
<ul>
<li><strong>Normal Mode</strong>: Default state for efficient movement, deletion, searching, and more.</li>
<li><strong>Insert Mode</strong>: Allows you to type text directly into your file.</li>
<li><strong>Visual Mode</strong>: Enables text selection for manipulation.</li>
</ul>
<h2 id="heading-how-to-navigate-using-vim-key-bindings">How to Navigate using Vim Key Bindings</h2>
<h3 id="heading-basic-movement">Basic Movement</h3>
<p>Here are some basic movement keys:</p>
<pre><code class="lang-plaintext">h  --&gt; move left
j  --&gt; move down
k  --&gt; move up
l  --&gt; move right
</code></pre>
<h3 id="heading-moving-to-top-and-bottom">Moving to Top and Bottom</h3>
<p>You can use these keys to move to the top or bottom of the page:</p>
<pre><code class="lang-plaintext">gg  --&gt; Move to the first line of the page
G   --&gt; Move to the last line of the page
</code></pre>
<h3 id="heading-moving-to-a-specific-line">Moving to a Specific Line</h3>
<p>You can move to a specific using <code>:</code> followed by the line number:</p>
<pre><code class="lang-plaintext">:number   --&gt; Go to the line number
</code></pre>
<h3 id="heading-moving-within-a-line">Moving Within a Line</h3>
<p>You can use these keys move to the start or end of a line:</p>
<pre><code class="lang-plaintext">$  --&gt; Go to the end of the line
0  --&gt; Go to the start of the line
</code></pre>
<h3 id="heading-moving-through-words">Moving Through Words</h3>
<p>Here are some keys for moving through lines of text:</p>
<pre><code class="lang-plaintext">b  --&gt; Go to the previous word
w  --&gt; Go to the next word
</code></pre>
<h2 id="heading-how-to-edit-text-in-normal-mode">How to Edit Text in Normal Mode</h2>
<h3 id="heading-deletion-and-copying">Deletion and Copying</h3>
<p>You can delete or copy characters using these keys:</p>
<pre><code class="lang-plaintext">x   --&gt; Delete the character under the cursor
dd  --&gt; Delete the entire line
yy  --&gt; Copy (yank) the entire line
p   --&gt; Paste the previously deleted or copied text after the cursor
</code></pre>
<h3 id="heading-undo-and-redo">Undo and Redo</h3>
<pre><code class="lang-plaintext">u          --&gt; Undo the last action
Ctrl + r   --&gt; Redo the undone action
</code></pre>
<h3 id="heading-searching-and-replacing">Searching and Replacing</h3>
<pre><code class="lang-plaintext">/              --&gt; Start searching forward
?              --&gt; Start searching backward
:s/old/new/g   --&gt; Replace all occurrences of "old" with "new" in the entire file
</code></pre>
<h2 id="heading-insert-mode">Insert Mode</h2>
<p>In Insert mode, you can type text directly into your file. Here are some key bindings to help you navigate in this mode:</p>
<pre><code class="lang-plaintext">Esc   --&gt; Return to Normal Mode
i     --&gt; Start inserting text before the cursor
a     --&gt; Start inserting text after the cursor
o     --&gt; Open a new line below the current line and start inserting text
</code></pre>
<h2 id="heading-visual-mode">Visual Mode</h2>
<p>Visual mode is useful for selecting and manipulating text visually. Here are some key bindings:</p>
<pre><code class="lang-plaintext">v          --&gt; Start character-wise visual mode
V          --&gt; Start line-wise visual mode
Ctrl + v   --&gt; Start block-wise visual mode
d          --&gt; Delete the selected text
y          --&gt; Copy (yank) the selected text
p          --&gt; Paste the copied text after the cursor
</code></pre>
<h2 id="heading-more-navigation-commands">More Navigation Commands</h2>
<h3 id="heading-scrolling">Scrolling</h3>
<pre><code class="lang-plaintext">Ctrl + u   --&gt; Move half a screen up
Ctrl + d   --&gt; Move half a screen down
Ctrl + b   --&gt; Move one full screen up
Ctrl + f   --&gt; Move one full screen down
</code></pre>
<h3 id="heading-jumping-between-words-and-paragraphs">Jumping between Words and Paragraphs</h3>
<pre><code class="lang-plaintext">(  --&gt; Jump to the beginning of the previous sentence
)  --&gt; Jump to the beginning of the next sentence
{  --&gt; Jump to the beginning of the previous paragraph
}  --&gt; Jump to the beginning of the next paragraph
</code></pre>
<p>These commands provide a comprehensive overview of the essential Vim key bindings for efficient navigation and text manipulation.</p>
<h2 id="heading-programming-specific-vim-key-bindings">Programming-Specific Vim Key Bindings</h2>
<h3 id="heading-moving-between-functions">Moving Between Functions</h3>
<p>In a code file, navigating between functions is a common task. Vim makes it efficient with these keys:</p>
<pre><code class="lang-plaintext">]]  --&gt; Move to the beginning of the next function
[[  --&gt; Move to the beginning of the previous function
</code></pre>
<p>These commands are invaluable for quickly jumping between different parts of your code.</p>
<h3 id="heading-indentation">Indentation</h3>
<p>Maintaining consistent code indentation is crucial. Vim enhances this with these keys:</p>
<pre><code class="lang-plaintext">&gt;&gt;  --&gt; Indent the current line to the right
&lt;&lt;  --&gt; Indent the current line to the left
</code></pre>
<p>Effortlessly adjust the indentation to adhere to coding standards and improve code readability.</p>
<h3 id="heading-folding">Folding</h3>
<p>Code folding aids in managing large files. Vim provides powerful folding commands:</p>
<pre><code class="lang-plaintext">zf{motion}  --&gt; Create a fold (replace {motion} with a movement command)
zo          --&gt; Open a fold
zc          --&gt; Close a fold
zr          --&gt; Reduce folding level throughout the file
zm          --&gt; Increase folding level throughout the file
</code></pre>
<p>Use folding to collapse and expand sections, this makes it easier to focus on specific parts of your code.</p>
<h3 id="heading-code-commenting">Code Commenting</h3>
<p>Efficiently comment and uncomment code with:</p>
<pre><code class="lang-plaintext">gcc  --&gt; Comment/uncomment the current line
gc{motion}  --&gt; Comment/uncomment the lines covered by {motion}
</code></pre>
<p>Speed up the commenting process and maintain code documentation effortlessly.</p>
<h3 id="heading-matching-parentheses">Matching Parentheses</h3>
<p>Effortlessly navigate and understand code structure with:</p>
<pre><code class="lang-plaintext">%  --&gt; Move to the matching parenthesis, bracket, or brace
</code></pre>
<p>This makes it easier to navigate complex code by quickly jumping between corresponding code blocks.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In essence, mastering Vim key bindings unlocks a world of efficient text editing. From basic movements to advanced coding tasks, Vim's modes and commands streamline navigation and manipulation. </p>
<p>By embracing these key bindings, you'll enhance productivity and enjoy a more seamless editing experience. Happy coding in Vim!</p>
<p>If you have any feedback, then you can DM me on <a target="_blank" href="https://twitter.com/introvertedbot">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/sahil-mahapatra/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Pass the Certified Kubernetes Security Specialist Exam – Cheat sheet and Study Guide ]]>
                </title>
                <description>
                    <![CDATA[ By Faizan Bashir This article is based on my experience studying for and passing the Certified Kubernetes Security Specialist exam. I passed the exam on my first attempt in Sep 2021. I passed the Certified Kubernetes Application Developer exam back i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-pass-the-certified-kubernetes-security-specialist-exam/</link>
                <guid isPermaLink="false">66d45ef4680e33282da25e6f</guid>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ exam  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Kubernetes ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 08 Mar 2022 17:40:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/cks.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Faizan Bashir</p>
<p>This article is based on my experience studying for and passing the Certified Kubernetes Security Specialist exam. I passed the exam on my first attempt in Sep 2021.</p>
<p>I passed the Certified Kubernetes Application Developer exam back in Feb 2020, followed by Certified Kubernetes Administrator in March 2020. </p>
<p>The Certified Kubernetes Security Specialist or CKS exam was released around November, 2020, but I didn't have a chance to take that exam before Sep 2021.</p>
<p>As a bit of background information, I have been working with Kubernetes for the past 3 years almost on a day-to-day basis and that experience was an added advantage in helping me pass the CKS.</p>
<p>In this article, I'll share some resources that should help you study for and pass the exam, along with a helpful cheatsheet you can use while preparing. I'll also share some advice that should help you along the way.</p>
<h3 id="heading-what-is-kubernetes">What is Kubernetes?</h3>
<p>Kubernetes is the most evolved and feature-rich Container Orchestration system out there, and it keeps getting better. </p>
<p>It has an enormous community to support, and it's always building new features and resolving issues. Kubernetes is certainly evolving at a breakneck pace, and it becomes a challenge to keep up with its pace of development. This makes it the best bet for a container orchestration solution.</p>
<hr>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ul>
<li><a class="post-section-overview" href="#heading-resources-for-the-exam">Resources for the CKS Exam</a></li>
<li><a class="post-section-overview" href="#heading-aliases">Aliases</a><ul>
<li><a class="post-section-overview" href="#heading-vi-defaults-for-vimrc">vi defaults for ~/.vimrc</a></li>
<li><a class="post-section-overview" href="#heading-kubectl-defaults-for-bashrc">kubectl defaults for ~/.bashrc</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-shortcuts">Shortcuts</a></li>
<li><a class="post-section-overview" href="#heading-kubernetes-cheat-sheet">Kubernetes Cheat Sheet</a><ul>
<li><a class="post-section-overview" href="#heading-kubectl-run-command">kubectl run command</a></li>
<li><a class="post-section-overview" href="#heading-how-to-generate-yaml-spec-from-an-existing-pod">How to generate yaml spec from an existing pod</a></li>
<li><a class="post-section-overview" href="#heading-kubectl-pod-commands">kubectl pod commands</a></li>
<li><a class="post-section-overview" href="#heading-how-to-print-logs-and-export-them">How to print logs and export them</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-config-maps-and-secrets">How to create configmaps and secrets</a></li>
<li><a class="post-section-overview" href="#heading-helpful-commands-for-debugging">Helpful commands for debugging</a></li>
<li><a class="post-section-overview" href="#heading-rolling-updates-and-rollouts">Rolling updates and rollouts</a></li>
<li><a class="post-section-overview" href="#heading-scale-and-autoscale-command">Scale and autoscale command</a></li>
<li><a class="post-section-overview" href="#heading-network-policy">Network policy</a></li>
<li><a class="post-section-overview" href="#heading-static-analysis-using-kubesec">Static analysis using Kubesec</a></li>
<li><a class="post-section-overview" href="#heading-vulnerability-scanning-using-trivvy">Vulnerability scanning using Trivvy</a></li>
<li><a class="post-section-overview" href="#heading-how-to-remove-unwanted-services">How to remove unwanted services</a></li>
<li><a class="post-section-overview" href="#heading-runtime-classes">Runtime classes</a></li>
<li><a class="post-section-overview" href="#heading-rbac-commands">RBAC commands</a></li>
<li><a class="post-section-overview" href="#heading-cluster-maintenance">Cluster maintenance</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-cks-exam-tips">CKS Exam Tips</a><ul>
<li><a class="post-section-overview" href="#heading-json-and-jsonpath">JSON and JSONPath</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-cks-exam-topics">CKS Exam Topics</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-secure-and-harden-container-images">How to secure and harden container images</a></li>
<li><a class="post-section-overview" href="#heading-how-to-minimise-os-footprint">How to minimise OS footprint</a><ul>
<li><a class="post-section-overview" href="#heading-conatiner-layers">Conatiner layers</a></li>
<li><a class="post-section-overview" href="#heading-multi-stage-builds">Multi stage builds</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-limit-node-access">How to limit node access</a></li>
<li><a class="post-section-overview" href="#heading-ssh-hardening">SSH hardening</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-disable-ssh">How to disable SSH</a></li>
<li><a class="post-section-overview" href="#heading-how-to-remove-obsolete-packages-and-services">How to remove obsolete packages and services</a></li>
<li><a class="post-section-overview" href="#heading-how-to-restrict-kernel-modules">How to restrict kernel modules</a></li>
<li><a class="post-section-overview" href="#heading-how-to-identify-and-disable-open-ports">How to identify and disable open ports</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-restrict-network-access">How to restrict network access</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-identity-a-service-running-on-port">How to identity a service running on port</a></li>
<li><a class="post-section-overview" href="#heading-ufw-firewall">UFW firewall</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-linux-syscalls">Linux syscalls</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-trace-syscalls-using-strace">How to trace Syscalls using Strace</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-aquasec-tracee">AquaSec tracee</a></li>
<li><a class="post-section-overview" href="#heading-how-to-restrict-syscalls-with-seccomp">How to restrict syscalls with Seccomp</a><ul>
<li><a class="post-section-overview" href="#heading-seccomp-in-kubernetes">Seccomp in Kubernetes</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-apparmor">AppArmor</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-use-apparmor-in-kubernetes">How to use AppArmor in Kubernetes</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-linux-capabilities">Linux capabilities</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-prepare-for-the-exam">How to Prepare for the Exam</a></li>
<li><a class="post-section-overview" href="#heading-practice-practice-and-practice">Practice, practice, and practice!</a></li>
</ul>
<hr>
<h2 id="heading-resources-for-the-exam">Resources for the Exam</h2>
<p>The following are a few awesome resources available on passing the CKS exam:</p>
<ol>
<li><a target="_blank" href="https://www.udemy.com/course/certified-kubernetes-security-specialist/">Certified Kubernetes Security Specialist by Killer.sh</a> </li>
<li><a target="_blank" href="https://kodekloud.com/courses/certified-kubernetes-security-specialist-cks/">Certified Kubernetes Security Specialist (CKS) by KodeKloud</a></li>
<li><a target="_blank" href="https://github.com/walidshaari/Certified-Kubernetes-Security-Specialist">Walid Shaari has gathered some indispensable materials for the CKS exam</a></li>
<li><a target="_blank" href="https://github.com/abdennour/certified-kubernetes-security-specialist">Abdennour's References for CKS Exam Objectives</a></li>
<li><a target="_blank" href="https://github.com/ibrahimjelliti/CKSS-Certified-Kubernetes-Security-Specialist">Ibrahim Jelliti's collection of resources to prepare for the Certified Kubernetes Security Specialist (CKSS) exam</a></li>
</ol>
<p>The courses for KodeKloud and Killer.sh provide mock exam simulators which are very helpful in preparing for the exam, and provide a pretty good idea of what the exam looks like. I strongly suggest enrolling in one or both courses. </p>
<p>Purchasing the exam from the Linux Foundation gives you 2 free attempts at the exam simulator from killer.sh. That way if you are well-versed with the contents of the curriculum you can skip the courses and directly go for the exam simulator provided with the exam.</p>
<p>The exam costs $375 but there are offers and deals available, and if you look for them you might be able to get a better price. The duration of the exam is 2 hours and is valid for 2 years, unlike the CKA and CKAD which are valid for 3 years.</p>
<h2 id="heading-aliases">Aliases</h2>
<p>The CKS is a performance-based exam where you are provided with an exam simulator in which you have to work out the problems. You are allowed to open only one tab apart from the exam tab. </p>
<p>Since this exam requires you to write a lot of commands, I figured early on that I'd have to rely on aliases to reduce the number of keystrokes to save time.</p>
<p>I used the <strong>vi</strong> editor during the exam, so here I will share some useful tips for this editor.</p>
<h3 id="heading-vi-defaults-for-vimrc">vi defaults for ~/.vimrc:</h3>
<pre><code>vi ~/.vimrc
---
:set number
:set et
:set sw=<span class="hljs-number">2</span> ts=<span class="hljs-number">2</span> sts=<span class="hljs-number">2</span>
---
^: Start <span class="hljs-keyword">of</span> word <span class="hljs-keyword">in</span> line
<span class="hljs-number">0</span>: Start <span class="hljs-keyword">of</span> line
<span class="hljs-attr">$</span>: End <span class="hljs-keyword">of</span> line
<span class="hljs-attr">w</span>: End <span class="hljs-keyword">of</span> word
<span class="hljs-attr">GG</span>: End <span class="hljs-keyword">of</span> file
</code></pre><h3 id="heading-kubectl-defaults-for-bashrc">kubectl defaults for ~/.bashrc:</h3>
<pre><code>vi ~/.bashrc
---
alias k=<span class="hljs-string">'kubectl'</span>
alias kg=<span class="hljs-string">'k get'</span>
alias kd=<span class="hljs-string">'k describe'</span>
alias kl=<span class="hljs-string">'k logs'</span>
alias ke=<span class="hljs-string">'k explain'</span>
alias kr=<span class="hljs-string">'k replace'</span>
alias kc=<span class="hljs-string">'k create'</span>
alias kgp=<span class="hljs-string">'k get po'</span>
alias kgn=<span class="hljs-string">'k get no'</span>
alias kge=<span class="hljs-string">'k get ev'</span>
alias kex=<span class="hljs-string">'k exec -it'</span>
alias kgc=<span class="hljs-string">'k config get-contexts'</span>
alias ksn=<span class="hljs-string">'k config set-context --current --namespace'</span>
alias kuc=<span class="hljs-string">'k config use-context'</span>
alias krun=<span class="hljs-string">'k run'</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">do</span>=<span class="hljs-string">'--dry-run=client -oyaml'</span>
<span class="hljs-keyword">export</span> force=<span class="hljs-string">'--grace-period=0 --force'</span>

source &lt;(kubectl completion bash)
source &lt;(kubectl completion bash | sed <span class="hljs-string">'s/kubectl/k/g'</span> )
complete -F __start_kubectl k


alias krp=<span class="hljs-string">'k run test --image=busybox --restart=Never'</span>
alias kuc=<span class="hljs-string">'k config use-context'</span>
---
</code></pre><h2 id="heading-shortcuts">Shortcuts</h2>
<p>The <code>kubectl get</code> command provides short catchy names for accessing resources and like <code>pvc</code> for <code>persistentstorageclaim</code>. These can help save a lot of keystrokes and valuable time during the exam.</p>
<ul>
<li><strong>po</strong> for <code>pods</code></li>
<li><strong>rs</strong> for <code>replicasets</code></li>
<li><strong>deploy</strong> for <code>deployments</code></li>
<li><strong>svc</strong> for <code>services</code></li>
<li><strong>ns</strong> for <code>namespace</code></li>
<li><strong>netpol</strong> for <code>networkpolicy</code></li>
<li><strong>pv</strong> for <code>persistentstorage</code></li>
<li><strong>pvc</strong> for <code>persistentstorageclaim</code></li>
<li><strong>sa</strong> for <code>serviceaccounts</code></li>
</ul>
<h2 id="heading-kubernetes-cheat-sheet">Kubernetes Cheat Sheet</h2>
<h3 id="heading-kubectl-run-command">kubectl run command</h3>
<p>The <code>kubectl run</code> command provides a flag <code>--restart</code> which allows you to create different kinds of Kubernetes objects from a Deployment to CronJob. </p>
<p>The below snippet shows the different options available for the <code>--restart</code> flag.</p>
<pre><code>k run:
--restart=Always                             #Creates a deployment
--restart=Never                              #Creates a Pod
--restart=OnFailure                          #Creates a Job
--restart=OnFailure --schedule=<span class="hljs-string">"*/1 * * * *"</span> #Creates a CronJob
</code></pre><h3 id="heading-how-to-generate-yaml-spec-from-an-existing-pod">How to generate yaml spec from an existing pod</h3>
<p>Sometimes it's easier to generate a spec from an existing pod and make changes to it than to create a new one from scratch. The <code>kubectl get pod</code> command provides us with the required flags to output the pod spec in the format we want.</p>
<pre><code>kgp &lt;pod-name&gt; -o wide

# Generating YAML Pod spec
kgp &lt;pod-name&gt; -o yaml
kgp &lt;pod-name&gt; -o yaml &gt; &lt;pod-name&gt;.yaml

# Get a pod's YAML spec without cluster specific information
kgp my-pod -o yaml --export &gt; &lt;pod-name&gt;.yaml
</code></pre><h3 id="heading-kubectl-pod-commands">kubectl pod commands</h3>
<p>The <code>kubectl run</code> command provides a lot of options, like specifying requests and the limits a pod is supposed to use or the commands a container should run once created.</p>
<pre><code># Output YAML <span class="hljs-keyword">for</span> a nginx pod running an echo command
krun nginx --image=nginx --restart=Never --dry-run -o yaml -- <span class="hljs-regexp">/bin/</span>sh -c <span class="hljs-string">'echo Hello World!'</span>
# Output YAML <span class="hljs-keyword">for</span> a busybox pod running a sleep command
krun busybox --image=busybox:<span class="hljs-number">1.28</span> --restart=Never --dry-run -o yaml -- <span class="hljs-regexp">/bin/</span>sh -c <span class="hljs-string">'while true; do echo sleep; sleep 10; done'</span>
# Run a pod <span class="hljs-keyword">with</span> set requests and limits
krun nginx --image=nginx --restart=Never --requests=<span class="hljs-string">'cpu=100m,memory=512Mi'</span> --limits=<span class="hljs-string">'cpu=300m,memory=1Gi'</span>
# Delete pod without delay
k <span class="hljs-keyword">delete</span> po busybox --grace-period=<span class="hljs-number">0</span> --force
</code></pre><h3 id="heading-how-to-print-logs-and-export-them">How to print logs and export them</h3>
<p>Logs are the fundamental source of information when it comes to debugging an application. The <code>kubectl logs</code> command provides the functionality to check the logs of a given pod. You can use the below commands to check the logs of a given pod.</p>
<pre><code>kubectl logs deploy/&lt;podname&gt;
kubectl logs deployment/&lt;podname&gt;
#Follow logs
kubectl logs deploy/&lt;podname&gt; --tail 1 --follow
</code></pre><p>Apart from just looking at logs, we can also export logs to a file for further debugging of sharing the same with anyone.</p>
<pre><code>kubectl logs &lt;podname&gt; --namespace &lt;ns&gt; &gt; <span class="hljs-regexp">/path/</span>to/file.format
</code></pre><h3 id="heading-how-to-create-config-maps-and-secrets">How to create config maps and secrets</h3>
<p>The <code>kubectl create</code> command lets us create ConfigMaps and Secrets from the command line. We can also use the YAML file to create the same resources and by using <code>kubectl apply -f &lt;filename&gt;</code> we can apply the commands.</p>
<pre><code>kc cm my-cm --<span class="hljs-keyword">from</span>-literal=APP_ENV=dev
kc cm my-cm --<span class="hljs-keyword">from</span>-file=test.txt
kc cm my-cm --<span class="hljs-keyword">from</span>-env-file=config.env

kc secret generic my-secret --<span class="hljs-keyword">from</span>-literal=APP_SECRET=sdcdcsdcsdcsdc
kc secret generic my-secret --<span class="hljs-keyword">from</span>-file=secret.txt
kc secret generic my-secret --<span class="hljs-keyword">from</span>-env-file=secret.env
</code></pre><h3 id="heading-helpful-commands-for-debugging">Helpful commands for debugging</h3>
<p>Debugging is a very important skill when you're facing issues and errors both in our day jobs and while solving problems in the CKS exam. </p>
<p>Apart from the ability to output logs from a container, the <code>kubectl exec</code> commands lets you log in to a running container and debug issues. While inside the container you can also use utilities like <code>nc</code> and <code>nslookup</code> to diagnose networking-related issues.</p>
<pre><code># Run busybox container
k run busybox --image=busybox:<span class="hljs-number">1.28</span> --rm --restart=Never -it sh
# Connect to a specific container <span class="hljs-keyword">in</span> a Pod
k exec -it busybox -c busybox2 -- <span class="hljs-regexp">/bin/</span>sh
# adding limits and requests <span class="hljs-keyword">in</span> command
kubectl run nginx --image=nginx --restart=Never --requests=<span class="hljs-string">'cpu=100m,memory=256Mi'</span> --limits=<span class="hljs-string">'cpu=200m,memory=512Mi'</span>
# Create a Pod <span class="hljs-keyword">with</span> a service
kubectl run nginx --image=nginx --restart=Never --port=<span class="hljs-number">80</span> --expose
# Check port
nc -z -v -w <span class="hljs-number">2</span> &lt;service-name&gt; &lt;port-name&gt;
# NSLookup
nslookup &lt;service-name&gt;
nslookup 10-32-0-10.default.pod
</code></pre><h3 id="heading-rolling-updates-and-rollouts">Rolling updates and rollouts</h3>
<p>The <code>kubectl rollout</code> command provides the ability to check for the status of updates and, if required, roll back to a previous version.</p>
<pre><code>k set image deploy/nginx nginx=nginx:<span class="hljs-number">1.17</span><span class="hljs-number">.0</span> --record
k rollout status deploy/nginx
k rollout history deploy/nginx
# Rollback to previous version
k rollout undo deploy/nginx
# Rollback to revision number
k rollout undo deploy/nginx --to-revision=<span class="hljs-number">2</span>
k rollout pause deploy/nginx
k rollout resume deploy/nginx
k rollout restart deploy/nginx
kubectl run nginx-deploy --image=nginx:<span class="hljs-number">1.16</span> --replias=<span class="hljs-number">1</span> --record
</code></pre><h3 id="heading-scale-and-autoscale-command">Scale and autoscale command</h3>
<p>The <code>kubectl scale</code> command provides the functionality to scale up or scale down pods in a given deployment. </p>
<p>Using the <code>kubectl autoscale</code> command we can define the minimum number of pods that should be running for a given deployment and the maximum numbers of pods the deployment can scale to along with the scaling criteria like CPU percentage.</p>
<pre><code>k scale deploy/nginx --replicas=<span class="hljs-number">6</span>
k autoscale deploy/nginx --min=<span class="hljs-number">3</span> --max=<span class="hljs-number">9</span> --cpu-percent=<span class="hljs-number">80</span>
</code></pre><h3 id="heading-network-policy">Network policy</h3>
<p>In a Kubernetes cluster, all pods can communicate with all pods by default, which can be a security issue in some implementations. </p>
<p>To get around this issue, Kubernetes introduced Network Policies to allow or deny traffic to and from pods based on pod labels which are part of the pod spec.</p>
<p>The below example denies both the Ingress and Egress traffic for pods running in all namespaces. </p>
<pre><code>apiVersion: networking.k8s.io/v1
<span class="hljs-attr">kind</span>: NetworkPolicy
<span class="hljs-attr">metadata</span>:
  name: example
  <span class="hljs-attr">namespace</span>: <span class="hljs-keyword">default</span>
<span class="hljs-attr">spec</span>:
  podSelector: {}
  <span class="hljs-attr">policyTypes</span>:
  - Egress
  - Ingress
</code></pre><p>The below example denies both the Ingress and Egress traffic for pods running in all namespaces. But it allows access to DNS resolution services running on port 53.</p>
<pre><code>apiVersion: networking.k8s.io/v1
<span class="hljs-attr">kind</span>: NetworkPolicy
<span class="hljs-attr">metadata</span>:
  name: deny
  <span class="hljs-attr">namespace</span>: <span class="hljs-keyword">default</span>
<span class="hljs-attr">spec</span>:
  podSelector: {}
  <span class="hljs-attr">policyTypes</span>:
  - Egress
  - Ingress
  <span class="hljs-attr">egress</span>:
  - to:
    ports:
      - port: <span class="hljs-number">53</span>
        <span class="hljs-attr">protocol</span>: TCP
      - port: <span class="hljs-number">53</span>
        <span class="hljs-attr">protocol</span>: UDP
</code></pre><p>The below example denies Egress access to the metadata server running on IP address <code>169.256.169.256</code> in AWS EC2 Instances.</p>
<pre><code>apiVersion: networking.k8s.io/v1
<span class="hljs-attr">kind</span>: Ingress
<span class="hljs-attr">metadata</span>:
  name:cloud-metadata-deny
  <span class="hljs-attr">namespace</span>: <span class="hljs-keyword">default</span>
<span class="hljs-attr">spec</span>:
  podSelector: {}
  <span class="hljs-attr">policyTypes</span>:
  - Egress
  <span class="hljs-attr">egress</span>:
  - to:
      - ipBlock: 
          cidr: <span class="hljs-number">0.0</span><span class="hljs-number">.0</span><span class="hljs-number">.0</span>/<span class="hljs-number">0</span>
          <span class="hljs-attr">except</span>:
          - <span class="hljs-number">169.256</span><span class="hljs-number">.169</span><span class="hljs-number">.256</span>/<span class="hljs-number">32</span>
</code></pre><p>The below example allows Egress access to the metadata server running on IP address <code>169.256.169.256</code> in AWS EC2 Instances.</p>
<pre><code>apiVersion: networking.k8s.io/v1
<span class="hljs-attr">kind</span>: Ingress
<span class="hljs-attr">metadata</span>:
  name: cloud-metadata-accessor
  <span class="hljs-attr">namespace</span>: <span class="hljs-keyword">default</span>
<span class="hljs-attr">spec</span>:
  podSelector:
    matchLabels:
      role: metadata-accessor
  <span class="hljs-attr">policyTypes</span>:
  - Egress
  <span class="hljs-attr">egress</span>:
  - to:
    - ipBlock:
        cidr: <span class="hljs-number">169.256</span><span class="hljs-number">.169</span><span class="hljs-number">.256</span>/<span class="hljs-number">32</span>
</code></pre><h3 id="heading-static-analysis-using-kubesec">Static analysis using Kubesec</h3>
<p>Kubesec is a Static Analysis tool for analyzing the YAML files to find issues with the files.</p>
<pre><code>kubesec scan pod.yaml

# Using online kubesec API
curl -sSX POST --data-binary @pod.yaml https:<span class="hljs-comment">//v2.kubesec.io/scan</span>

# Running the API locally
kubesec http <span class="hljs-number">8080</span> &amp;

kubesec scan pod.yaml -o pod_report.json -o json
</code></pre><h3 id="heading-vulnerability-scanning-using-trivvy">Vulnerability scanning using Trivvy</h3>
<p>Trivvy is a Vulnerability Scanning tool that scans container images for security issues.</p>
<pre><code>trivy image nginx:<span class="hljs-number">1.18</span><span class="hljs-number">.0</span>
trivy image --severity CRITICAL nginx:<span class="hljs-number">1.18</span><span class="hljs-number">.0</span>
trivy image --severity CRITICAL, HIGH nginx:<span class="hljs-number">1.18</span><span class="hljs-number">.0</span>
trivy image --ignore-unfixed nginx:<span class="hljs-number">1.18</span><span class="hljs-number">.0</span>

# Scanning image tarball
docker save nginx:<span class="hljs-number">1.18</span><span class="hljs-number">.0</span> &gt; nginx.tar
trivy image --input archive.tar

# Scan and output results to file
trivy image --output python_alpine.txt python:<span class="hljs-number">3.10</span><span class="hljs-number">.0</span>a4-alpine
trivy image --severity HIGH --output /root/python.txt python:<span class="hljs-number">3.10</span><span class="hljs-number">.0</span>a4-alpine

# Scan image tarball
trivy image --input alpine.tar --format json --output /root/alpine.json
</code></pre><h3 id="heading-how-to-remove-unwanted-services">How to remove unwanted services</h3>
<p>The <code>systemctl</code> exposes the capabilities to start, stop, enable, disable and list services running on a Linux Virtual Machine.</p>
<p>List services:</p>
<pre><code>systemctl list-units --type service
</code></pre><p>Stop Service:</p>
<pre><code>systemctl stop apache2
</code></pre><p>Disable Service:</p>
<pre><code>systemctl disable apache2
</code></pre><p>Remove Service:</p>
<pre><code>apt remove apache2
</code></pre><h3 id="heading-runtime-classes">Runtime classes</h3>
<p>Kubernetes introduced the RuntimeClass feature in version <code>v1.12</code> for selecting the container runtime configuration. The container runtime configuration is used to run a pod's underlying containers. </p>
<p>Most Kubernetes clusters use the <code>dockershim</code> as the Runtime class for the running containers, but you can use different container Runtimes. </p>
<p>The <code>dockershim</code> has been deprecated in Kubernetes version <code>v1.20</code>, and will be removed in <code>v1.24</code>.</p>
<p>How to create a Runtime Class:</p>
<pre><code>apiversion: node.k8s.io/v1beta1
<span class="hljs-attr">kind</span>: RuntimeClass
<span class="hljs-attr">metadata</span>:
  name: gvisor
<span class="hljs-attr">handler</span>: runsc
</code></pre><p>How to use a runtime class for any given pod:</p>
<pre><code>apiVersion: v1
<span class="hljs-attr">kind</span>: Pod
<span class="hljs-attr">metadata</span>:
  labels:
    run: nginx
  <span class="hljs-attr">name</span>: nginx
<span class="hljs-attr">spec</span>:
  runtimeClassName: gvisor
  <span class="hljs-attr">containers</span>:
  - name: nginx
    <span class="hljs-attr">image</span>: nginx
</code></pre><h3 id="heading-rbac-commands">RBAC commands</h3>
<p>In Kubernetes, </p>
<blockquote>
<p>Role-based access control (RBAC) commands provide a method of regulating access to Kubernetes resources based on the roles of individual users or service accounts. (<a target="_blank" href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">Source</a>)</p>
</blockquote>
<p>Here's how to create a role:</p>
<pre><code>kubectl create role developer --resource=pods --verb=create,list,get,update,<span class="hljs-keyword">delete</span> --namespace=development
</code></pre><p>How to create a role binding:</p>
<pre><code>kubectl create rolebinding developer-role-binding --role=developer --user=faizan --namespace=development
</code></pre><p>How to validate:</p>
<pre><code>kubectl auth can-i update pods --namespace=development --<span class="hljs-keyword">as</span>=faizan
</code></pre><p>How to create a cluster role:</p>
<pre><code>kubectl create clusterrole pvviewer-role --resource=persistentvolumes --verb=list
</code></pre><p>And how to create a Clusterrole Binding association with a service account:</p>
<pre><code>kubectl create clusterrolebinding pvviewer-role-binding --clusterrole=pvviewer-role --serviceaccount=<span class="hljs-keyword">default</span>:pvviewer
</code></pre><h3 id="heading-cluster-maintenance">Cluster maintenance</h3>
<p>You use the <code>kubectl drain</code> command to remove all running workloads (pods) from a given Node. </p>
<p>You use the <code>kubectl cordon</code> command to cordon a node to mark it as schedulable. </p>
<p>Ands you use the <code>kubectl uncordon</code> command to set the node as schedulable, meaning the Controller Manager can schedule new pods to the given node.</p>
<p>How to drain a node of all pods:</p>
<pre><code>kubectl drain node<span class="hljs-number">-1</span>
</code></pre><p>How to drain a node and ignore daemonsets:</p>
<pre><code>kubectl drain node01 --ignore-daemonsets
</code></pre><p>How to force drain:</p>
<pre><code>kubectl drain node02 --ignore-daemonsets --force
</code></pre><p>How to mark a node un-schedulable, so that no new pods can be scheduled on this node:</p>
<pre><code>kubectl cordon node<span class="hljs-number">-1</span>
</code></pre><p>Mark a node schedulable</p>
<pre><code>kubectl uncordon node<span class="hljs-number">-1</span>
</code></pre><h2 id="heading-cks-exam-tips">CKS Exam Tips</h2>
<p>The Kubernetes <code>kubectl get</code> command provides the user with an output flag, <code>-o</code> or <code>--output</code>, which helps us format the output in the form of JSON, yaml, wide, or custom-columns.</p>
<h3 id="heading-json-and-jsonpath">JSON and JSONPath</h3>
<p>How to output the contents of all the pods in the form of a JSON Object:</p>
<pre><code>kubectl get pods -o json
</code></pre><p>The JSONPath outputs a specific key from the JSON Object:</p>
<pre><code>kubectl get pods -o=jsonpath=<span class="hljs-string">'{@}'</span>
kubectl get pods -o=jsonpath=<span class="hljs-string">'{.items[0]}'</span>
</code></pre><p>The <code>.items[*]</code> is used where we have multiple objects, for instance multiple containers with a pod config:</p>
<pre><code># For list <span class="hljs-keyword">of</span> items use .items[*]
k get pods -o <span class="hljs-string">'jsonpath={.items[*].metadata.labels.version}'</span>
# For single item
k get po busybox -o jsonpath=<span class="hljs-string">'{.metadata}'</span>
k get po busybox -o jsonpath=<span class="hljs-string">"{['.metadata.name', '.metadata.namespace']}{'\n'}"</span>
</code></pre><p>The command returns the internal IP of a Node using JSONPath:</p>
<pre><code>kubectl get nodes -o=jsonpath=<span class="hljs-string">'{.items[*].status.addresses[?(@.type=="InternalIP")].address}'</span>
</code></pre><p>The command checks for equality on a specific key:</p>
<pre><code>kubectl get pod api-stag<span class="hljs-number">-765797</span>cf-lrd8q -o=jsonpath=<span class="hljs-string">'{.spec.volumes[?(@.name=="api-data")].persistentVolumeClaim.claimName}'</span>
kubectl get pod -o=jsonpath=<span class="hljs-string">'{.items[*].spec.tolerations[?(@.effect=="NoSchedule")].key}'</span>
</code></pre><p>Custom Columns are helpful in order to output specific fields:</p>
<pre><code>kubectl get pods -o=<span class="hljs-string">'custom-columns=PODS:.metadata.name,Images:.spec.containers[*].image'</span>
</code></pre><h2 id="heading-cks-exam-topics">CKS Exam Topics</h2>
<p>The CKS exam covers topics related to security in the Kubernetes ecosystem. Kubernetes security is a vast topic to cover in one article, so this article contains some of the topics covered in the exam.</p>
<h3 id="heading-how-to-secure-and-harden-container-images">How to secure and harden container images</h3>
<p>While designing container images to run your code, pay special attention to securing and hardening measures in order to prevent hacks and privilege escalation attacks. Keep the below points in mind while building the container images:</p>
<ol>
<li>Use specific package versions like <code>alpine:3.13</code>.</li>
<li>Don't run as root – use the <code>USER &lt;username&gt;</code> to block root access.</li>
<li>Make filesystem read-only in the <code>securityContext</code> using <code>readOnlyRootFilesystem: true</code></li>
<li>Remove shell access using <code>RUN rm -rf /bin/*</code></li>
</ol>
<h3 id="heading-how-to-minimise-os-footprint">How to minimise OS footprint</h3>
<h4 id="heading-conatiner-layers">Conatiner layers</h4>
<p>The instructions <code>RUN</code>, <code>COPY</code>, and <code>ADD</code> create container layers. Other instructions create temporary intermediate images and do not increase the size of the build. Instructions that create layers add to the size of the resulting image.</p>
<p>A typical Dockerfile looks like the one given below. It adds a single layer using the <code>RUN</code> instruction.</p>
<pre><code>FROM ubuntu

RUN apt-get update &amp;&amp; apt-get install -y golang-go

CMD [<span class="hljs-string">"sh"</span>]
</code></pre><h4 id="heading-multi-stage-builds">Multi-stage builds</h4>
<p>Multi-Stage builds leverage multiple <code>FROM</code> statements in the Dockerfile. The <code>FROM</code> instruction marks a new stage in the build. It combines multiple <code>FROM</code> statements allow to leverage from the previous build in order to selectively copy binaries over to the new build stage omitting the unnecessary binaries. The resulting Docker image is considerably smaller in size with a drastically reduced attack surface.</p>
<pre><code>FROM ubuntu:<span class="hljs-number">20.04</span> AS build
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update &amp;&amp; apt-get install -y golang-go
COPY app.go .
RUN CGO_ENABLED=<span class="hljs-number">0</span> go build app.go

FROM alpine:<span class="hljs-number">3.13</span>
RUN chmod a-w /etc
RUN addgroup -S appgroup &amp;&amp; adduser -S appuser -G appgroup -h /home/appuser
RUN rm -rf /bin<span class="hljs-comment">/*
COPY --from=build /app /home/appuser/
USER appuser
CMD ["/home/appuser/app"]</span>
</code></pre><h3 id="heading-how-to-limit-node-access">How to limit node access</h3>
<p>Access Control files contain sensitive information about users/groups in the Linux OS.</p>
<pre><code>#Stores information about the UID/GID, user shell, and home directory <span class="hljs-keyword">for</span> a user
/etc/passwd
#Stores the user password <span class="hljs-keyword">in</span> a hashed format
/etc/shadow
#Stores information about the group a user belongs
/etc/group
#Stored information about the Sudoers present <span class="hljs-keyword">in</span> the system
/etc/sudoers
</code></pre><p>Disabling a user account helps in securing access to a Node by disabling login to a given user account.</p>
<pre><code>usermod -s /bin/nologin &lt;username&gt;
</code></pre><p>Disabling the <code>root</code> user account is of special significance, as the root account has all the capabilities.</p>
<pre><code>usermod -s /bin/nologin root
</code></pre><p>Here's how to add a user with a home directory and shell:</p>
<pre><code>adduser --home /opt/faizanbashir --shell /bin/bash --uid <span class="hljs-number">2328</span> --ingroup admin faizanbashir
useradd -d /opt/faizanbashir -s /bin/bash -G admin -u <span class="hljs-number">2328</span> faizanbashir
</code></pre><p>How to delete the user account:</p>
<pre><code>userdel &lt;username&gt;
</code></pre><p>How to delete a group:</p>
<pre><code>groupdel &lt;groupname&gt;
</code></pre><p>How to add a user to a group:</p>
<pre><code>adduser &lt;username&gt; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">groupname</span>&gt;</span></span>
</code></pre><p>How to remove a user from a group:</p>
<pre><code>#deluser faizanbashir admin
deluser &lt;username&gt; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">groupname</span>&gt;</span></span>
</code></pre><p>How to set a password for a user:</p>
<pre><code>passwd &lt;username&gt;
</code></pre><p>How to elevate a user to sudoer:</p>
<pre><code>vim /etc/sudoers
&gt;&gt;&gt;
faizanbashir ALL=(ALL:ALL) ALL
</code></pre><p>How to enable sudo with no password:</p>
<pre><code>vim /etc/sudoers
&gt;&gt;&gt;
faizanbashir ALL=(ALL) NOPASSWD:ALL

visudo
usermod -aG sudo faizanbashir
usermod faizanbashir -G admin
</code></pre><h3 id="heading-ssh-hardening">SSH hardening</h3>
<h4 id="heading-how-to-disable-ssh">How to disable SSH</h4>
<p>The configuration given in the <code>/etc/ssh/sshd_config</code> can be leveraged to secure SSH access to Linux nodes. Setting the <code>PermitRootLogin</code> to <code>no</code> disables the root login on a node. </p>
<p>To enforce using a key to login and disabling login using passwords to nodes, you can set the <code>PasswordAuthentication</code> to <code>no</code>.</p>
<pre><code>vim /etc/ssh/sshd_config
&gt;&gt;
PermitRootLogin no
PasswordAuthentication no
&lt;&lt;
# Restart SSHD Service
systemctl restart sshd
</code></pre><p>How to set no login for the root user:</p>
<pre><code>usermod -s /bin/nologin root
</code></pre><p>SSH Copy user key / Passwordless SSH:</p>
<pre><code>ssh-copy-id -i ~<span class="hljs-regexp">/.ssh/i</span>d_rsa.pub faizanbashir@node01
ssh faizanbashir@node01
</code></pre><h3 id="heading-how-to-remove-obsolete-packages-and-services">How to remove obsolete packages and services</h3>
<p>Here's how you can list all services running on an Ubuntu machine:</p>
<pre><code>systemctl list-units --type service
systemctl list-units --type service --state running
</code></pre><p>How to stop, disable, and remove a service:</p>
<pre><code>systemctl stop apache2
systemctl disable apache2
apt remove apache2
</code></pre><h3 id="heading-how-to-restrict-kernel-modules">How to restrict kernel modules</h3>
<p>In Linux, Kernel modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system. A module can be configured as built-in or loadable.</p>
<p>How to list all Kernel Modules:</p>
<pre><code>lsmod
</code></pre><p>How to manually load modules into a Kernel:</p>
<pre><code>modprobe pcspkr
</code></pre><p>How to blacklist a module: (Reference: CIS Benchmarks -&gt; 3.4 Uncommon Network Protocols)</p>
<pre><code>cat /etc/modprobe.d/blacklist.conf
&gt;&gt;&gt;
blacklist sctp
blacklist dccp

# Shutdown <span class="hljs-keyword">for</span> changes to take effect
shutdown -r now

# Verify
lsmod | grep dccp
</code></pre><h3 id="heading-how-to-identify-and-disable-open-ports">How to identify and disable open ports</h3>
<p>How to check for open ports:</p>
<pre><code>netstat -an | grep -w LISTEN
netstat -natp | grep <span class="hljs-number">9090</span>

nc -zv &lt;hostname|IP&gt; <span class="hljs-number">22</span>
nc -zv &lt;hostname|IP&gt; <span class="hljs-number">10</span><span class="hljs-number">-22</span>

ufw deny <span class="hljs-number">8080</span>
</code></pre><p>How to check port usage:</p>
<pre><code>/etc/services | grep -w <span class="hljs-number">53</span>
</code></pre><p>Here's the reference doc for a <a target="_blank" href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/#control-plane-node-s">list of open ports</a>.</p>
<h3 id="heading-how-to-restrict-network-access">How to restrict network access</h3>
<h4 id="heading-how-to-identity-a-service-running-on-port">How to identity a service running on port:</h4>
<pre><code>systemctl status ssh
cat /etc/services | grep ssh
netstat -an | grep <span class="hljs-number">22</span> | grep -w LISTEN
</code></pre><h4 id="heading-ufw-firewall">UFW firewall</h4>
<p>Uncomplicated Fire Wall (UFW) is a tool for managing firewall rules in Arch Linux, Debian, or Ubuntu. UFW lets you allow and block traffic on a given port and from a given source.</p>
<p>Here's how to install UFW Firewall:</p>
<pre><code>apt-get update
apt-get install ufw
systemctl enable ufw
systemctl start ufw
ufw status
ufw status numbered
</code></pre><p>How to allow all outbound and inbound connections:</p>
<pre><code>ufw <span class="hljs-keyword">default</span> allow outgoing
ufw <span class="hljs-keyword">default</span> allow incoming
</code></pre><p>How to allow rules:</p>
<pre><code>ufw allow <span class="hljs-number">22</span>
ufw allow <span class="hljs-number">1000</span>:<span class="hljs-number">2000</span>/tcp
ufw allow <span class="hljs-keyword">from</span> <span class="hljs-number">172.16</span><span class="hljs-number">.238</span><span class="hljs-number">.5</span> to any port <span class="hljs-number">22</span> proto tcp
ufw allow <span class="hljs-keyword">from</span> <span class="hljs-number">172.16</span><span class="hljs-number">.238</span><span class="hljs-number">.5</span> to any port <span class="hljs-number">80</span> proto tcp
ufw allow <span class="hljs-keyword">from</span> <span class="hljs-number">172.16</span><span class="hljs-number">.100</span><span class="hljs-number">.0</span>/<span class="hljs-number">28</span> to any port <span class="hljs-number">80</span> proto tcp
</code></pre><p>How to deny rules:</p>
<pre><code>ufw deny <span class="hljs-number">8080</span>
</code></pre><p>How to enable and activate the Firewall:</p>
<pre><code>ufw enable
</code></pre><p>How to delete rules:</p>
<pre><code>ufw <span class="hljs-keyword">delete</span> deny <span class="hljs-number">8080</span>
ufw <span class="hljs-keyword">delete</span> &lt;rule-line&gt;
</code></pre><p>How to reset rules:</p>
<pre><code>ufw reset
</code></pre><h3 id="heading-linux-syscalls">Linux Syscalls</h3>
<p>Linux Syscalls are used to make requests from user space into the Linux kernel. For instance, while creating a file, the userspace makes a request to the Linux Kernel to create the file. </p>
<p>Kernel Space has the following:</p>
<ul>
<li>Kernel Code</li>
<li>Kernel Extensions</li>
<li>Device Drivers</li>
</ul>
<h4 id="heading-how-to-trace-syscalls-using-strace">How to trace Syscalls using Strace</h4>
<p>Here's how you can trace syscalls using strace:</p>
<pre><code>which strace
strace touch /tmp/error.log
</code></pre><p>How to get the PID of a service:</p>
<pre><code>pidof sshd
strace -p &lt;pid&gt;
</code></pre><p>How to list all syscalls made during an operation:</p>
<pre><code>strace -c touch /tmp/error.log
</code></pre><p>How to consolidate listing syscalls: (Count and summarise)</p>
<pre><code>strace -cw ls /
</code></pre><p>How to follow a PID and consolidate:</p>
<pre><code>strace -p <span class="hljs-number">3502</span> -f -cw
</code></pre><h3 id="heading-aquasec-tracee">AquaSec Tracee</h3>
<p>AquaSec Tracee was created by Aqua Security which uses eBPF to trace events in containers. Tracee uses eBPF (Extended Berkeley Packet Filter) at runtime directly in the kernel space without interfering with the kernel source or loading any kernel modules.</p>
<ul>
<li>Binary stored at <code>/tmp/tracee</code></li>
<li>Needs access to the following, in read-only mode if run using a container with <code>--privileged</code> capability:<ul>
<li><code>/tmp/tracee</code> -&gt; Default workspace</li>
<li><code>/lib/modules</code> -&gt; Kernel Headers</li>
<li><code>/usr/src</code> -&gt; Kernel Headers</li>
</ul>
</li>
</ul>
<p>How to fun Tracee in a Docker container:</p>
<pre><code>docker run --name tracee --rm --privileged --pid=host \
  -v /lib/modules/:<span class="hljs-regexp">/lib/m</span>odules/:ro -v /usr/src/:<span class="hljs-regexp">/usr/</span>src/ro \
  -v /tmp/tracee:<span class="hljs-regexp">/tmp/</span>tracee aquasec/tracee:<span class="hljs-number">0.4</span><span class="hljs-number">.0</span> --trace comm=ls

# List syscalls made by all the <span class="hljs-keyword">new</span> process on the host
docker run --name tracee --rm --privileged --pid=host \
  -v /lib/modules/:<span class="hljs-regexp">/lib/m</span>odules/:ro -v /usr/src/:<span class="hljs-regexp">/usr/</span>src/ro \
  -v /tmp/tracee:<span class="hljs-regexp">/tmp/</span>tracee aquasec/tracee:<span class="hljs-number">0.4</span><span class="hljs-number">.0</span> --trace pid=<span class="hljs-keyword">new</span>

# List syscalls made <span class="hljs-keyword">from</span> any <span class="hljs-keyword">new</span> container
docker run --name tracee --rm --privileged --pid=host \
  -v /lib/modules/:<span class="hljs-regexp">/lib/m</span>odules/:ro -v /usr/src/:<span class="hljs-regexp">/usr/</span>src/ro \
  -v /tmp/tracee:<span class="hljs-regexp">/tmp/</span>tracee aquasec/tracee:<span class="hljs-number">0.4</span><span class="hljs-number">.0</span> --trace container=<span class="hljs-keyword">new</span>
</code></pre><h3 id="heading-how-to-restrict-syscalls-with-seccomp">How to restrict Syscalls with Seccomp</h3>
<p><strong>SECCOMP</strong> – Secure Computing Mode – is a Linux Kernel level feature that you can use to sandbox applications to only use the syscalls they need.</p>
<p>How to check support for seccomp:</p>
<pre><code>grep -i seccomp /boot/config-$(uname -r)
</code></pre><p>How to test to change system time:</p>
<pre><code>docker run -it --rm docker/whalesay /bin/sh
# date -s <span class="hljs-string">'19 APR 2013 22:00:00'</span>

ps -ef
</code></pre><p>How to check seccomp status for any PID:</p>
<pre><code>grep -i seccomp /proc/<span class="hljs-number">1</span>/status
</code></pre><p>Seccomp modes:</p>
<ul>
<li>Mode 0: Disabled</li>
<li>Mode 1: Strict</li>
<li>Mode 2: Filtered</li>
</ul>
<p>The following configuration is used to whitelist syscalls. The whitelist profile is secure but syscalls have to be selectively enabled as it blocks all syscalls by default.</p>
<pre><code>{
  <span class="hljs-string">"defaultAction"</span>: <span class="hljs-string">"SCMP_ACT_ERRNO"</span>,
  <span class="hljs-string">"architectures"</span>: [
    <span class="hljs-string">"SCMP_ARCH_X86_64"</span>,
    <span class="hljs-string">"SCMP_ARCH_X86"</span>,
    <span class="hljs-string">"SCMP_ARCH_X32"</span>
  ],
  <span class="hljs-string">"syscalls"</span>: [
    {
      <span class="hljs-string">"names"</span>: [
        <span class="hljs-string">"&lt;syscall-1&gt;"</span>,
        <span class="hljs-string">"&lt;syscall-2&gt;"</span>,
        <span class="hljs-string">"&lt;syscall-3&gt;"</span>
      ],
      <span class="hljs-string">"action"</span>: <span class="hljs-string">"SCMP_ACT_ALLOW"</span>
    }
  ]
}
</code></pre><p>The following configuration is used to blacklist syscalls. The blacklist profile has a greater attack surface than the whitelist. </p>
<pre><code>{
  <span class="hljs-string">"defaultAction"</span>: <span class="hljs-string">"SCMP_ACT_ALLOW"</span>,
  <span class="hljs-string">"architectures"</span>: [
    <span class="hljs-string">"SCMP_ARCH_X86_64"</span>,
    <span class="hljs-string">"SCMP_ARCH_X86"</span>,
    <span class="hljs-string">"SCMP_ARCH_X32"</span>
  ],
  <span class="hljs-string">"syscalls"</span>: [
    {
      <span class="hljs-string">"names"</span>: [
        <span class="hljs-string">"&lt;syscall-1&gt;"</span>,
        <span class="hljs-string">"&lt;syscall-2&gt;"</span>,
        <span class="hljs-string">"&lt;syscall-3&gt;"</span>
      ],
      <span class="hljs-string">"action"</span>: <span class="hljs-string">"SCMP_ACT_ERRNO"</span>
    }
  ]
}
</code></pre><p>The Docker seccomp profile blocks 60 of the 300+ syscalls on the x86 architecture.</p>
<p>How to use seccomp profiles with Docker:</p>
<pre><code>docker run -it --rm --security-opt seccomp=<span class="hljs-regexp">/root/</span>custom.json docker/whalesay /bin/sh
</code></pre><p>How to allow all syscalls with the container:</p>
<pre><code>docker run -it --rm --security-opt seccomp=unconfined docker/whalesay /bin/sh

# Verify
grep -i seccomp /proc/<span class="hljs-number">1</span>/status

# Output should be:
Seccomp:         <span class="hljs-number">0</span>
</code></pre><p>How to use Docker container to get container runtime related information:</p>
<pre><code>docker run r.j3ss.co/amicontained amicontained
</code></pre><h4 id="heading-seccomp-in-kubernetes">Seccomp in Kubernetes</h4>
<p>Secure computing mode (SECCOMP) is a Linux kernel feature. You can use it to restrict the actions available within the container. <a target="_blank" href="https://kubernetes.io/docs/tutorials/clusters/seccomp">Seccomp documentation</a></p>
<p>How to run amicontained in Kubernetes:</p>
<pre><code>kubectl run amicontained --image r.j3ss.co/amicontained amicontained -- amicontained
</code></pre><p>As of version <code>v1.20</code> Kubernetes does not implement seccomp by default.</p>
<p>Seccomp 'RuntimeDefault' docker profile in Kubernetes:</p>
<pre><code>apiVersion: v1
<span class="hljs-attr">kind</span>: Pod
<span class="hljs-attr">metadata</span>:
  labels:
    run: amicontained
  <span class="hljs-attr">name</span>: amicontained
<span class="hljs-attr">spec</span>:
  securityContext:
    seccompProfile:
      type: RuntimeDefault
  <span class="hljs-attr">containers</span>:
  - args:
    - amicontained
    <span class="hljs-attr">image</span>: r.j3ss.co/amicontained
    <span class="hljs-attr">name</span>: amicontained
    <span class="hljs-attr">securityContext</span>:
      allowPrivilegeEscalation: <span class="hljs-literal">false</span>
</code></pre><p>Default seccomp location in kubelets</p>
<pre><code>/<span class="hljs-keyword">var</span>/lib/kubelet/seccomp
</code></pre><p>How to create a seccomp profile in node:</p>
<pre><code>mkdir -p /<span class="hljs-keyword">var</span>/lib/kubelet/seccomp/profiles

# Add a profile <span class="hljs-keyword">for</span> audit
vim /<span class="hljs-keyword">var</span>/lib/kubelet/seccomp/profiles/audit.json
&gt;&gt;&gt;
{
  <span class="hljs-attr">defaultAction</span>: <span class="hljs-string">"SCMP_ACT_LOG"</span>
}

# Add a profile <span class="hljs-keyword">for</span> violations (Blocks all syscalls by <span class="hljs-keyword">default</span>, will <span class="hljs-keyword">let</span> nothing run)
vim /<span class="hljs-keyword">var</span>/lib/kubelet/seccomp/profiles/violation.json
&gt;&gt;&gt;
{
  <span class="hljs-attr">defaultAction</span>: <span class="hljs-string">"SCMP_ACT_ERRNO"</span>
}
</code></pre><p>Local seccomp profile – this file should exist locally on a node to be able to work:</p>
<pre><code>...
securityContext:
  seccompProfile:
    type: Localhost
    <span class="hljs-attr">localhostProfile</span>: profiles/audit.json
...
</code></pre><p>The above profile will enable syscalls to be saved to a file.</p>
<pre><code>grep syscall /<span class="hljs-keyword">var</span>/log/syslog
</code></pre><p>How to map syscall numbers to syscall name:</p>
<pre><code>grep -w <span class="hljs-number">35</span> /usr/include/asm/unistd_64.h

# OR
grep -w <span class="hljs-number">35</span> /usr/include/asm-generic/unistd.h
</code></pre><h3 id="heading-apparmor">AppArmor</h3>
<p>AppArmor is a Linux security module that is used to confine a program to a limited set of resources.</p>
<p>How to install AppArmor utils:</p>
<pre><code>apt-get install apparmor-utils
</code></pre><p>How to check if AppArmor is running and enabled:</p>
<pre><code>systemctl status apparmor

cat /sys/<span class="hljs-built_in">module</span>/apparmor/parameters/enabled
Y
</code></pre><p>The AppArmor profiles are stored at:</p>
<pre><code>cat /etc/apparmor.d/root.add_data.sh
</code></pre><p>How to list AppArmor profiles:</p>
<pre><code>cat /sys/kernel/security/apparmor/profiles
</code></pre><p>How to deny all file write profiles:</p>
<pre><code>profile apparmor-deny-write flags=(attach_disconnected) {
  file,
  # Deny all file writes.
  deny <span class="hljs-comment">/** w,
}</span>
</code></pre><p>How to deny write to <code>/proc</code> files:</p>
<pre><code>profile apparmor-deny-proc-write flags=(attach_disconnected) {
  file,
  # Deny all file writes.
  deny /proc<span class="hljs-comment">/* w,
}</span>
</code></pre><p>How to deny remount root FS:</p>
<pre><code>profile apparmor-deny-remount-root flags=(attach_disconnected) {

  # Deny all file writes.
  deny mount options=(ro, remount) -&gt; /,
}
</code></pre><p>How to check profile status:</p>
<pre><code>aa-status
</code></pre><p>Profile load modes</p>
<ul>
<li><code>Enforce</code>, monitor and enforce the rules</li>
<li><code>Complain</code>, will not enforce the rules but logs them as events</li>
<li><code>Unconfined</code>, will not enforce or log events</li>
</ul>
<p>How to check if a profile is valid:</p>
<pre><code>apparmor_parser /etc/apparmor.d/root.add_data.sh
</code></pre><p>How to disable a profile:</p>
<pre><code>apparmor_parser -R /etc/apparmor.d/root.add_data.sh
ln -s /etc/apparmor.d/root.add_data.sh /etc/apparmor.d/disable/
</code></pre><p>How to generate a profile and answer the series of questions that follow:</p>
<pre><code>aa-genprof /root/add_data.sh
</code></pre><p>How to generate a profile for a command:</p>
<pre><code>aa-genprof curl
</code></pre><p>How to disable profile from logs:</p>
<pre><code>aa-logprof
</code></pre><h4 id="heading-how-to-use-apparmor-in-kubernetes">How to use AppArmor in Kubernetes</h4>
<p>To use AppArmor with Kubernetes, the following prerequisites must be met:</p>
<ul>
<li>Kubernetes version should be greater than <code>1.4</code></li>
<li>AppArmor Kernel module should be enabled</li>
<li>AppArmor profile should be loaded in the kernel</li>
<li>Container runtime should be supported</li>
</ul>
<p>Sample usage in Kubernetes:</p>
<pre><code>apiVersion: v1
<span class="hljs-attr">kind</span>: Pod
<span class="hljs-attr">metadata</span>:
  name: ubuntu-sleeper
  <span class="hljs-attr">annotations</span>:
    container.apparmor.security.beta.kubernetes.io/&lt;container-name&gt;: localhost/&lt;profile-name&gt;
spec:
  containers:
  - name: ubuntu-sleeper
    image: ubuntu
    command: ["sh", "-c", "echo 'Sleeping for an hour!' &amp;&amp; sleep 1h"]
</code></pre><p><strong>Note</strong>: The container should run in a node containing the AppArmor profile.</p>
<h3 id="heading-linux-capabilities">Linux capabilities</h3>
<p>The Linux capabilities feature breaks up the privileges available to processes run as the <code>root</code> user into smaller groups of privileges. This way a process running with <code>root</code> privilege can be limited to get only the minimal permissions it needs to perform its operation. </p>
<p>Docker supports the Linux capabilities as part of the Docker run command: with <code>--cap-add</code> and <code>--cap-drop</code>. By default, a container is started with several capabilities that are allowed by default and can be dropped. Other permissions can be added manually. </p>
<p>Both <code>--cap-add</code> and <code>--cap-drop</code> support the ALL value, to allow or drop all capabilities. By default Docker containers run with 14 capabilities.</p>
<ul>
<li>Kernel &lt; 2.2<ul>
<li>Privileged Process</li>
<li>Unprivileged Process</li>
</ul>
</li>
<li>Kernel &gt;= 2.2<ul>
<li>Privileged Process<ul>
<li><code>CAP_CHOWN</code></li>
<li><code>CAP_SYS_TIME</code></li>
<li><code>CAP_SYS_BOOT</code></li>
<li><code>CAP_NET_ADMIN</code></li>
</ul>
</li>
</ul>
</li>
</ul>
<p><a target="_blank" href="https://man7.org/linux/man-pages/man7/capabilities.7.html">Refer to this document for the full list of Linux Capabilities</a>.</p>
<p>How to check what capabilities a command needs:</p>
<pre><code>getcap /usr/bin/ping
</code></pre><p>How to get process capabilities:</p>
<pre><code>getpcaps &lt;pid&gt;
</code></pre><p>How to add security capabilities:</p>
<pre><code>apiVersion: v1
<span class="hljs-attr">kind</span>: Pod
<span class="hljs-attr">metadata</span>:
  name: ubuntu-sleeper
<span class="hljs-attr">spec</span>:
  containers:
  - name: ubuntu-sleeper
    <span class="hljs-attr">image</span>: ubuntu
    <span class="hljs-attr">command</span>: [<span class="hljs-string">"sleep"</span>, <span class="hljs-string">"1000"</span>]
    <span class="hljs-attr">securityContext</span>:
      capabilities:
        add: [<span class="hljs-string">"SYS_TIME"</span>]
        <span class="hljs-attr">drop</span>: [<span class="hljs-string">"CHOWN"</span>]
</code></pre><h2 id="heading-how-to-prepare-for-the-exam">How to Prepare for the Exam</h2>
<p>CKS is considered a pretty tough exam. But based on my experience I think that, given good enough practice and if you understand the concepts the exam covers, it'll be pretty manageable within two hours. </p>
<p>You definitely need to understand the underlying Kubernetes concepts. And since a prerequisite for CKS is to pass the CKA exam, you should have a strong understanding of Kubernetes and how it functions before attempting the CKS. </p>
<p>In addition, to pass the CKS, you need to understand the threats and security implications introduced by container orchestration.</p>
<p>The introduction of the CKS exam is an indication that the security of containers should not be taken lightly. Security mechanisms should always be in place to thwart attacks on Kubernetes clusters. </p>
<p>The <a target="_blank" href="https://www.wired.com/story/cryptojacking-tesla-amazon-cloud/">Tesla cryptocurrency hack</a> that was thanks to an unprotected Kubernetes dashboard brings to light the risks associated with Kubernetes or any other container orchestration engine. <a target="_blank" href="https://hackerone.com/kubernetes?type=team">Hackerone has a Kubernetes bounty page</a> listing the source code repos used in a standard Kubernetes cluster.</p>
<h2 id="heading-practice-practice-and-practice">Practice, Practice, and Practice!</h2>
<p>Practice is the key to cracking the exam, I personally found that the exam simulators by KodeKloud and Killer.sh were immensely helpful for me.</p>
<p>I didn't have as much time to prepare for the CKS exam as I had for the CKA exam, but I was working on Kubernetes in my day job so I'd become really comfortable with it. </p>
<p>Practice is the key to success. Best of luck with the exam!</p>
<p><em>You can read this and other articles at <a target="_blank" href="https://faizanbashir.me/rough-guide-to-qualifying-the-cks-exam-in-a-hurry">faizanbashir.me</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The React Cheatsheet for 2022 ]]>
                </title>
                <description>
                    <![CDATA[ Do you want to get up to speed with React as quickly as possible? I’ve put together a super helpful cheatsheet to give you a complete overview of all of the React concepts you need to know in 2022. Click here to download the cheatsheet in PDF format.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-react-cheatsheet/</link>
                <guid isPermaLink="false">66d037f6ab216b4115759486</guid>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Mon, 14 Feb 2022 17:02:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/mugshotbot.com_customize_theme-two_up-mode-light-color-pink-pattern-bubbles-image-9129875b-url-https___freecodecamp.org.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Do you want to get up to speed with React as quickly as possible?</p>
<p>I’ve put together a super helpful cheatsheet to give you a complete overview of all of the React concepts you need to know in 2022.</p>
<p><a target="_blank" href="https://reedbarger.com/resources/the-react-cheatsheet-for-2021">Click here to download the cheatsheet in PDF format</a>.</p>
<p>It includes all of the essential information in this article as a convenient PDF guide.</p>
<p>Let’s get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-react-elements">React Elements</a></li>
<li><a class="post-section-overview" href="#heading-react-element-attributes">React Element Attributes</a></li>
<li><a class="post-section-overview" href="#heading-react-element-styles">React Element Styles</a></li>
<li><a class="post-section-overview" href="#heading-react-fragments">React Fragments</a></li>
<li><a class="post-section-overview" href="#heading-react-components">React Components</a></li>
<li><a class="post-section-overview" href="#heading-react-props">React Props</a></li>
<li><a class="post-section-overview" href="#heading-react-children-props">React Children Props</a></li>
<li><a class="post-section-overview" href="#heading-react-conditionals">React Conditionals</a></li>
<li><a class="post-section-overview" href="#heading-react-lists">React Lists</a></li>
<li><a class="post-section-overview" href="#heading-react-context">React Context</a></li>
<li><a class="post-section-overview" href="#heading-react-hooks">React Hooks</a></li>
<li><a class="post-section-overview" href="#heading-react-usestate-hook">React useState Hook</a></li>
<li><a class="post-section-overview" href="#heading-react-useeffect-hook">React useEffect Hook</a></li>
<li><a class="post-section-overview" href="#heading-react-useref">React useRef Hook</a></li>
<li><a class="post-section-overview" href="#heading-react-usecontext">React useContext Hook</a></li>
<li><a class="post-section-overview" href="#heading-react-usecallback">React useCallback Hook</a></li>
<li><a class="post-section-overview" href="#heading-react-usememo">React useMemo Hook</a></li>
</ul>
<h2 id="heading-react-elements">React Elements</h2>
<p>React elements are written just like regular HTML elements. You can write any valid HTML element in React.</p>
<pre><code class="lang-js">&lt;h1&gt;My Header&lt;/h1&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>My paragraph&gt;
<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>My button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
</code></pre>
<p>We write React elements using a feature called <em>JSX</em>.</p>
<p>However, because JSX is really just JavaScript functions (and not HTML), the syntax is a bit different.</p>
<p>Unlike HTML, single-tag elements (like the img element), must be self-closing. They must end in a forward slash <code>/</code>:</p>
<pre><code class="lang-js">&lt;img src=<span class="hljs-string">"my-image.png"</span> /&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">hr</span> /&gt;</span></span>
</code></pre>
<h2 id="heading-react-element-attributes">React Element Attributes</h2>
<p>Additionally, JSX requires a different syntax for its attributes.</p>
<p>Since JSX is really JavaScript and JavaScript uses a camelcase naming convention (that is, “camelCase”), attributes are written differently than HTML.</p>
<p>The most common example is the <code>class</code> attribute, which we write as <code>className</code>.</p>
<pre><code class="lang-js">&lt;div className=<span class="hljs-string">"container"</span>&gt;&lt;/div&gt;
</code></pre>
<h2 id="heading-react-element-styles">React Element Styles</h2>
<p>To apply inline styles, instead of using double quotes (“”), we use two sets of curly braces.</p>
<p>Inline styles are not written as plain strings, but as properties on objects:</p>
<pre><code class="lang-js">&lt;h1 style={{ <span class="hljs-attr">fontSize</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">margin</span>: <span class="hljs-string">'0 auto'</span>, <span class="hljs-attr">textAlign</span>: <span class="hljs-string">'center'</span> }}&gt;My header&lt;/h1&gt;
</code></pre>
<h2 id="heading-react-fragments">React Fragments</h2>
<p>React also gives us an element called a <em>fragment</em>.</p>
<p>React requires that all returned elements be returned within a single “parent” component.</p>
<p>For example, we can’t return two sibling elements, like an h1 and a paragraph from a component:</p>
<pre><code><span class="hljs-comment">// this syntax is invalid</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
    &lt;<span class="hljs-regexp">/p&gt;My paragraph&lt;/</span>p&gt;
  );
}
</code></pre><p>If we don’t want to wrap our elements in a container element like a div, we can use a fragment:</p>
<pre><code><span class="hljs-comment">// valid syntax</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>My paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre><p>We can write fragments in a regular or shorthand syntax:  or &lt;&gt;&lt;/&gt;.</p>
<h2 id="heading-react-components">React Components</h2>
<p>We can organized groups of elements into React components.</p>
<p>A basic function component is written similarly to a regular JavaScript function with a couple of differences.</p>
<ol>
<li>Component names must start with a capital letter (that is, MyComponent, instead of myComponent)</li>
<li>Components, unlike JavaScript functions, must return JSX.</li>
</ol>
<p>Here is the basic syntax of a React function component:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
     <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Hello world!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><h2 id="heading-react-props">React Props</h2>
<p>React components can accept data passed to them called <em>props</em>.</p>
<p>Props are passed from the parent component to a child component.</p>
<p>Here we are passing a prop <code>name</code> from App to the User component.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">User</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"John Doe"</span> /&gt;</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>; <span class="hljs-comment">// Hello, John Doe!</span>
}
</code></pre><p>Props is an object, so we can select the <code>name</code> prop within <code>User</code> to get its value.</p>
<blockquote>
<p>To embed any dynamic value (that is, a variable or expression) within JSX, you must wrap it in curly braces.</p>
</blockquote>
<p>Since we are only using the <code>name</code> property on the props object, we can make our code simpler with object destructuring:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">User</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"John Doe"</span> /&gt;</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">{ name }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, {name}!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>; <span class="hljs-comment">// Hello, John Doe!</span>
}
</code></pre><p>Any JavaScript value can be passed as a prop, including other elements and components.</p>
<h2 id="heading-react-children-props">React Children Props</h2>
<p>Props can also be passed by placing data between the opening and closing tags of a component.</p>
<p>Props that are passed this way are placed on the <code>children</code> property.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">User</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, John Doe!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">User</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params">{ children }</span>) </span>{
  <span class="hljs-keyword">return</span> children; <span class="hljs-comment">// Hello, John Doe!</span>
}
</code></pre><h2 id="heading-react-conditionals">React Conditionals</h2>
<p>React components and elements can be conditionally displayed.</p>
<p>One approach is to create a separate return with an if-statement.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> isAuthUser = useAuth();

  <span class="hljs-keyword">if</span> (isAuthUser) {
    <span class="hljs-comment">// if our user is authenticated, let them use the app</span>
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AuthApp</span> /&gt;</span></span>;
  }

  <span class="hljs-comment">// if user is not authenticated, show a different screen</span>
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">UnAuthApp</span> /&gt;</span></span>;
}
</code></pre><p>If you want to write a conditional within a return statement, however, you must use a conditional that resolves to a value.</p>
<p>To use the ternary operator, wrap the entire conditional in curly braces.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> isAuthUser = useAuth();

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {isAuthUser ? <span class="hljs-tag">&lt;<span class="hljs-name">AuthApp</span> /&gt;</span> : <span class="hljs-tag">&lt;<span class="hljs-name">UnAuthApp</span> /&gt;</span>}
    <span class="hljs-tag">&lt;/&gt;</span></span>
  ) 
}
</code></pre><h2 id="heading-react-lists">React Lists</h2>
<p>Lists of React components can be output using the <code>.map()</code> function.</p>
<p><code>.map()</code> allows us to loop over arrays of data and output JSX.</p>
<p>Here we are outputting a list of soccer players using the SoccerPlayer component.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SoccerPlayers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> players = [<span class="hljs-string">"Messi"</span>, <span class="hljs-string">"Ronaldo"</span>, <span class="hljs-string">"Laspada"</span>];

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {players.map((playerName) =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">SoccerPlayer</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{playerName}</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{playerName}</span> /&gt;</span>
      ))}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><p>Whenever you are looping over an array of data, you must include the <em>key</em> prop on the element or component over which you are looping.</p>
<p>Additionally, this key prop must be given a unique value, not just an element index.</p>
<p>In the example above, we are using a value which we know to be unique, which is the <code>playerName</code>.</p>
<h2 id="heading-react-context">React Context</h2>
<p>React context allows us to pass data to our component tree without using props.</p>
<p>The problem with props is that sometimes we pass them through components that don’t need to receive them. This problem is called <em>props drilling</em>.</p>
<p>Here is a oversimplified example of passing props through a <code>Body</code> component that doesn’t need it:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Body</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"John Doe"</span> /&gt;</span></span>
  );
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Body</span>(<span class="hljs-params">{ name }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Greeting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{name}</span> /&gt;</span></span>
  );
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params">{ name }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome, {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre><blockquote>
<p>Before using Context, its best to see if our components can be better organized to avoid passing props through components that don’t need it.</p>
</blockquote>
<p>To use Context, we use the <code>createContext</code> function from React.</p>
<p>We can call it with an initial value to be put on context.</p>
<p>The created context includes a <code>Provider</code> and a <code>Consumer</code> property, which are each components.</p>
<p>We wrap the Provider around the component tree that we want to pass the given value down. Next, we place the Consumer in the component we want to consume the value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> NameContext = createContext(<span class="hljs-string">''</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    &lt;NameContext.Provider value="John Doe"&gt;
      &lt;Body /&gt;
    &lt;NameContext.Provider&gt;
  );
} 

function Body() {
  return &lt;Greeting /&gt;;
} 

function Greeting() {
  return (
    &lt;NameContext.Consumer&gt;
      {name =&gt; &lt;h1&gt;Welcome, {name}&lt;/h1&gt;}
    &lt;/NameContext.Consumer&gt;
  );
}
</code></pre>
<h2 id="heading-react-hooks">React Hooks</h2>
<p>React hooks were introduced in React version 16.8 as a way to easily add reusable, stateful logic to React function components.</p>
<p>Hooks let us use all the features that were previously only available in class components.</p>
<p>Additionally, we can create our own custom hooks that give our app custom functionality.</p>
<p>Many React hooks were added to the core React library as well. We are going to cover the 6 essential hooks you absolutely need to know:</p>
<ul>
<li>useState</li>
<li>useEffect</li>
<li>useRef</li>
<li>useContext</li>
<li>useCallback</li>
<li>useMemo</li>
</ul>
<h2 id="heading-react-usestate-hook">React useState Hook</h2>
<p><code>useState</code> does exactly what it says—it allows us to use stateful values in function components.</p>
<p>useState is used instead of a simple variable because when state is updated, our component re-renders, usually to display that updated value.</p>
<p>Like all hooks, we call <code>useState</code> at the top of our component and can pass it an initial value to put on its state variable.</p>
<p>We use array destructuring on the value returned from <code>useState</code> to access (1) the stored state and (2) a function to update that state.</p>
<pre><code><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [stateValue, setStateValue] = useState(initialValue);
}
</code></pre><p>A basic example of using <code>useState</code> is to increment a counter.</p>
<p>We can see the current count from the <code>count</code> variable and can increment the state by passing <code>count + 1</code> to the <code>setCount</code> function.</p>
<pre><code><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCount</span>(<span class="hljs-params"></span>) </span>{
    setCount(count + <span class="hljs-number">1</span>);
  }

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateCount}</span>&gt;</span>Count is: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
}
</code></pre><h2 id="heading-react-useeffect-hook">React useEffect Hook</h2>
<p>If we want to interact with the “outside world”, such as using an API, we use the <code>useEffect</code> hook.</p>
<p>useEffect is used to perform a side effect, which means to perform an operation that exists outside of our app that doesn’t have a predictable result.</p>
<p>The basic syntax of useEffect requires a function as a first argument and an array as the second argument.</p>
<pre><code><span class="hljs-keyword">import</span> { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-comment">// perform side effect here</span>
   }, []);
}
</code></pre><p>If we want to fetch data, we would use <code>useEffect</code>, such as in fetching and displaying a list of posts:</p>
<pre><code><span class="hljs-keyword">import</span> { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PostList</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-keyword">const</span> [posts, setPosts] = useState([]);

   useEffect(<span class="hljs-function">() =&gt;</span> {
       fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts'</span>)
       .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
       .then(<span class="hljs-function"><span class="hljs-params">posts</span> =&gt;</span> setPosts(posts));
   }, []);

   <span class="hljs-keyword">return</span> posts.map(<span class="hljs-function"><span class="hljs-params">post</span> =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Post</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{post.id}</span> <span class="hljs-attr">post</span>=<span class="hljs-string">{post}</span> /&gt;</span></span>
}
</code></pre><p>If we need to use a value that comes from outside the effect function, it must be included in the dependencies array.</p>
<p>If that value changes, the effect function will be re-executed.</p>
<p>For example, here is a bit of code that adds or removes the class “overflow-hidden” to the body element whenever the mobile menu is opened or closed.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Mobile</span>(<span class="hljs-params">{ open }</span>) </span>{
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#__next"</span>);

    <span class="hljs-keyword">if</span> (open) {
      body.classList.add(<span class="hljs-string">"overflow-hidden"</span>);
    } <span class="hljs-keyword">else</span> {
      body.classList.remove(<span class="hljs-string">"overflow-hidden"</span>);
    }
  }, [open]);

  <span class="hljs-comment">// ...</span>
}
</code></pre><h2 id="heading-react-useref">React useRef</h2>
<p><code>useRef</code> allows us to get direct access to a JSX element.</p>
<p>To use <code>useRef</code>, call it, get the returned value, and put it on the <code>ref</code> prop for a given React element.</p>
<blockquote>
<p>Refs do not have a built-in prop on components, only React elements.</p>
</blockquote>
<p>Here is the basic syntax for <code>useRef</code>:</p>
<pre><code><span class="hljs-keyword">import</span> { useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> ref = useRef();

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{ref}</span> /&gt;</span></span>
}
</code></pre><p>Once a ref is attached to a given element, we can use the value stored on <code>ref.current</code> to access the element itself.</p>
<p>For example, if we wanted to write some code that focuses a search input when the users use the key combination Control + K.</p>
<pre><code><span class="hljs-keyword">import</span> { useWindowEvent } <span class="hljs-keyword">from</span> <span class="hljs-string">"@mantine/hooks"</span>;
<span class="hljs-keyword">import</span> { useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> inputRef = useRef();

  useWindowEvent(<span class="hljs-string">"keydown"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (event.code === <span class="hljs-string">"KeyK"</span> &amp;&amp; event.ctrlKey) {
      event.preventDefault();
      inputRef.current.focus();
    }
  });

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span></span>
}
</code></pre><h2 id="heading-react-usecontext">React useContext</h2>
<p><code>useContext</code> provides an easier way of consuming context than using the standard Context.Consumer component.</p>
<p>The syntax involves passing the entire Context object that we want to consume into <code>useContext</code>. The returned value is the value passed down to Context.</p>
<pre><code><span class="hljs-keyword">import</span> { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> value = useContext(Context);

  <span class="hljs-comment">// ...</span>
}
</code></pre><p>To rewrite our example from earlier, using the <code>useContext</code> hook:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createContext, useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> NameContext = createContext(<span class="hljs-string">''</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    &lt;NameContext.Provider value="John Doe"&gt;
      &lt;Body /&gt;
    &lt;NameContext.Provider&gt;
  );
} 

function Body() {
  return &lt;Greeting /&gt;;
} 

function Greeting() {
    const name = useContext(NameContext);

  return (
    &lt;h1&gt;Welcome, {name}&lt;/h1&gt;
  );
}
</code></pre>
<h2 id="heading-react-usecallback">React useCallback</h2>
<p><code>useCallback</code> is a hook that we use to help with our app's performance.</p>
<p>Specifically, it prevents functions from being recreated every time our component re-renders, which can hurt the performance of our app.</p>
<p>If we go back to our <code>PlayerList</code> example from earlier and add the ability to add players to our array, when we pass down a function to remove them (<code>handleRemovePlayer</code>) via props, the function will be recreated every time.</p>
<p>The way to fix this is to wrap our callback function in <code>useCallback</code> and to include its one argument <code>player</code> in the dependencies array:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [player, setPlayer] = React.useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [players, setPlayers] = React.useState([<span class="hljs-string">"Messi"</span>, <span class="hljs-string">"Ronaldo"</span>, <span class="hljs-string">"Laspada"</span>]);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleChangeInput</span>(<span class="hljs-params">event</span>) </span>{
    setPlayer(event.target.value);
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleAddPlayer</span>(<span class="hljs-params"></span>) </span>{
    setPlayers(players.concat(player));
  }
  <span class="hljs-keyword">const</span> handleRemovePlayer = useCallback(<span class="hljs-function"><span class="hljs-params">player</span> =&gt;</span> {
    setPlayers(players.filter(<span class="hljs-function">(<span class="hljs-params">p</span>) =&gt;</span> p !== player));
  }, [players])

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChangeInput}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleAddPlayer}</span>&gt;</span>Add Player<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">PlayerList</span> <span class="hljs-attr">players</span>=<span class="hljs-string">{players}</span> <span class="hljs-attr">handleRemovePlayer</span>=<span class="hljs-string">{handleRemovePlayer}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PlayerList</span>(<span class="hljs-params">{ players, handleRemovePlayer }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {players.map((player) =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{player}</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> handleRemovePlayer(player)}&gt;
          {player}
        <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      ))}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
  );
}
</code></pre><h2 id="heading-react-usememo">React useMemo</h2>
<p><code>useMemo</code> is another performance hook that allows us to ‘memoize’ a given operation.</p>
<p>Memoization makes it possible to remember the result of expensive calculations when they have already been made so we don’t have to make them again.</p>
<p>Like <code>useEffect</code> and <code>useCallback</code>, <code>useMemo</code> accepts a callback function and a dependencies array.</p>
<p>Unlike both of these functions, however, <code>useMemo</code> is intended to return a value.</p>
<blockquote>
<p>You must return the value either explicitly with the <code>return</code> keyword or implicitly but using the arrow function shorthand (seen below).</p>
</blockquote>
<p>A real-world example of <code>useMemo</code> comes from the mdx-bundler documentation. <code>mdx-bundler</code> is a library for converting .mdx files into React components.</p>
<p>Here it uses <code>useMemo</code> to convert a raw string of code into a React component.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> {getMDXComponent} <span class="hljs-keyword">from</span> <span class="hljs-string">'mdx-bundler/client'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Post</span>(<span class="hljs-params">{code, frontmatter}</span>) </span>{
  <span class="hljs-keyword">const</span> Component = React.useMemo(<span class="hljs-function">() =&gt;</span> getMDXComponent(code), [code]);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{frontmatter.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{frontmatter.description}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Component</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>The reason for doing so is to prevent the <code>Component</code> value from being recreated unnecessarily when the component re-renders.</p>
<p><code>useMemo</code> therefore will only execute its callback function if the <code>code</code> dependency changes.</p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ HTML Cheat Sheet – HTML Elements List Reference ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, we will go over commonly used HTML tags, elements, and attributes. We'll also see examples of how these tags, elements, and attributes work. You can use this article as a reference guide whether you're a beginner or experienced deve... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/html-cheat-sheet-html-elements-list-reference/</link>
                <guid isPermaLink="false">66b0a2f6b30dd4d00547bb9f</guid>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ reference ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 03 Feb 2022 17:00:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/html-cheat-sheet.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, we will go over commonly used HTML tags, elements, and attributes. We'll also see examples of how these tags, elements, and attributes work.</p>
<p>You can use this article as a reference guide whether you're a beginner or experienced developer.</p>
<h2 id="heading-what-makes-up-an-html-document">What Makes Up an HTML Document?</h2>
<p>The following tags define the basic HTML document structure:</p>
<ul>
<li><code>&lt;html&gt;</code> tag – This tag acts as a container for every other element in the document except the <code>&lt;!DOCTYPE _html_&gt;</code> tag. </li>
<li><code>&lt;head&gt;</code> tag– Includes all the document's metadata. </li>
<li><code>&lt;title&gt;</code> tag – Defines the title of the document which is displayed in the browser's title bar.</li>
<li><code>&lt;body&gt;</code> tag – Acts as a container for the document's content that gets displayed on the browser.</li>
</ul>
<p>Here's what all that looks like:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span> My HTML Cheat Sheet <span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><code>&lt;!DOCTYPE _html_&gt;</code> specifies that we are working with an HTML5 document.</p>
<p>The following tags give additional information to the HTML document:</p>
<ul>
<li><code>&lt;meta&gt;</code> tag – This tag can be used to define additional information about the webpage.</li>
<li><code>&lt;link&gt;</code> tag – Used to link the document to an external resource.</li>
<li><code>&lt;style&gt;</code> tag – Used for defining styles for the document. </li>
<li><code>&lt;script&gt;</code> tag – Used to write code snippets (usually JavaScript) or to link the document to an external script.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>My HTML Cheat Sheet<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
      * {
        <span class="hljs-attribute">font-size</span>: <span class="hljs-number">100px</span>;
      }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      alert(<span class="hljs-string">'This is an alert'</span>);
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
</code></pre>
<h2 id="heading-html-document-structure">HTML Document Structure</h2>
<p>When you're fleshing out your HTML document, you'll use certain tags to create the structure.</p>
<p>The <code>&lt;h1&gt;</code> to <code>&lt;h6&gt;</code> tags show different levels of headings in a document, with </p><h1 id="heading-being-the-largest-and"> being the largest and </h1><h6 id="heading-being-the-smallest-heading-1-heading-2-heading-3-heading-4-heading-5-heading-6-you-use-the-tag-to-create-a-paragraph-this-is-a-paragraph-the-tag-can-be-used-to-divide-and-style-separate-sections-of-the-document-it-also-acts-as-a-parent-container-for-other-elements-heres-how-it-works-this-is-the-news-section-welcome-to-the-news-section-this-is-the-contact-us-section-hello-world-we-also-have-the-tag-this-is-similar-to-but-you-use-it-as-an-inline-container-i-love-coding-theres-the-tag-which-we-use-for-creating-line-breaks-this-has-no-closing-tag-i-love-freecodecamp-the-tag-is-used-to-create-a-horizontal-line-it-also-has-no-closing-tag"> being the smallest.<p></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Heading 1 <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span> Heading 2 <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span> Heading 3 <span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span> Heading 4 <span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h5</span>&gt;</span> Heading 5 <span class="hljs-tag">&lt;/<span class="hljs-name">h5</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h6</span>&gt;</span> Heading 6 <span class="hljs-tag">&lt;/<span class="hljs-name">h6</span>&gt;</span>
</code></pre>
<p>You use the <code>&lt;p&gt;</code> tag to create a paragraph.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> This is a paragraph <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>The <code>&lt;div&gt;</code> tag can be used to divide and style separate sections of the document. It also acts as a parent container for other elements. Here's how it works:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"newsSection"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> This is the news section <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Welcome to the news section! <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"contactSection"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> This is the contact us section <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Hello world! <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>We also have the <code>&lt;span&gt;</code> tag. This is similar to <code>&lt;div&gt;</code> but you use it as an inline container. </p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> I love <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"keyword"</span>&gt;</span> coding! <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>There's the <code>&lt;br/&gt;</code> tag, which we use for creating line breaks. This has no closing tag.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> I love <span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span> freeCodeCamp <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>The <code>&lt;hr/&gt;</code> tag is used to create a horizontal line. It also has no closing tag.</p>
</h6><h2 id="heading-images-in-html">Images in HTML</h2>
<p>In HTML, we use the <code>&lt;img/&gt;</code> tag to display images. </p>
<p>Here are some attributes of the <code>&lt;img/&gt;</code> tag:</p>
<ul>
<li><code>src</code> is used to specify the path to the location of the image on your computer or the web.</li>
<li><code>alt</code> defines an alternate text that displays if the image cannot be rendered. The alt text is also good for screen readers.</li>
<li><code>height</code> specifies the height of the image.</li>
<li><code>width</code> specifies the width of the image.</li>
<li><code>border</code> specifies the thickness of the borders, which is set to 0 if no border is added.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"ihechikara.png"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"a picture of Ihechikara"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"300"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"300"</span>&gt;</span>
</code></pre>
<h2 id="heading-text-formatting-in-html">Text Formatting in HTML</h2>
<p>We have many ways to format text in HTML. Let's go over them now briefly.</p>
<ul>
<li><code>&lt;i&gt;</code> displays text in italics.</li>
<li><code>&lt;b&gt;</code> displays text in bold. </li>
<li><code>&lt;strong&gt;</code> displays text in bold. Used to make important emphasis.</li>
<li><code>&lt;em&gt;</code> another emphasis tag that displays text in italics.</li>
<li><code>&lt;sub&gt;</code> defines subscript text, like the two atoms of oxygen in CO₂.</li>
<li><code>&lt;sup&gt;</code> defines a superscript like the power of a number, 10².</li>
<li><code>&lt;small&gt;</code> reduces the size of text.</li>
<li><code>&lt;del&gt;</code> defines deleted text by striking a line through the text.</li>
<li><code>&lt;ins&gt;</code> defines inserted text which is usually underlined. </li>
<li><code>&lt;blockquote&gt;</code> is used to enclose a section of text quoted from another source.</li>
<li><code>&lt;q&gt;</code> is used for shorter inline quotes.</li>
<li><code>&lt;cite&gt;</code> is used for citing the author of a quote.</li>
<li><code>&lt;address&gt;</code> is used for showing the author's contact information.</li>
<li><code>&lt;abbr&gt;</code> denotes an abbreviation.</li>
<li><code>&lt;code&gt;</code> displays code snippets.</li>
<li><code>&lt;mark&gt;</code> highlights text.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span>&gt;</span> italic text <span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">b</span>&gt;</span>bold text <span class="hljs-tag">&lt;/<span class="hljs-name">b</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span> strong text <span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">em</span>&gt;</span> strong text <span class="hljs-tag">&lt;/<span class="hljs-name">em</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">sub</span>&gt;</span> subscripted text <span class="hljs-tag">&lt;/<span class="hljs-name">sub</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">sup</span>&gt;</span> superscripted text <span class="hljs-tag">&lt;/<span class="hljs-name">sup</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">small</span>&gt;</span> small text <span class="hljs-tag">&lt;/<span class="hljs-name">small</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">del</span>&gt;</span> deleted text <span class="hljs-tag">&lt;/<span class="hljs-name">del</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">ins</span>&gt;</span> inserted text <span class="hljs-tag">&lt;/<span class="hljs-name">ins</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">blockquote</span>&gt;</span> quoted text <span class="hljs-tag">&lt;/<span class="hljs-name">blockquote</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">q</span>&gt;</span> short quoted text <span class="hljs-tag">&lt;/<span class="hljs-name">q</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">cite</span>&gt;</span> cited text <span class="hljs-tag">&lt;/<span class="hljs-name">cite</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">address</span>&gt;</span> address <span class="hljs-tag">&lt;/<span class="hljs-name">address</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">abbr</span>&gt;</span> inserted text <span class="hljs-tag">&lt;/<span class="hljs-name">abbr</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span> code snippet <span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">mark</span>&gt;</span> marked text <span class="hljs-tag">&lt;/<span class="hljs-name">mark</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<h2 id="heading-links">Links</h2>
<p>The <code>&lt;a&gt;</code> tag, also known as the anchor tag, is used to define hyperlinks that link to other pages (external web pages included) or to a section of the same page.</p>
<p>Here are some attributes of the <code>&lt;a&gt;</code> tag:</p>
<ul>
<li><code>href</code> specifies the URL the link takes the user to when clicked.</li>
<li><code>download</code> specifies that the target or resource clicked is downloadable.</li>
<li><code>target</code> specifies where the link is to be opened. This could be in the same or separate window.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.freecodecamp.org/"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span> Learn to code <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre>
<h2 id="heading-lists">Lists</h2>
<p>The <code>&lt;ol&gt;</code> tag defines an ordered list while the <code>&lt;ul&gt;</code> tag defines an unordered list.</p>
<p>The <code>&lt;li&gt;</code> tag is used to create items in the list.</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- Unordered list --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> HTML <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> CSS <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> JavaScrip t<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>

<span class="hljs-comment">&lt;!-- Ordered list --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ol</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> HTML <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> CSS <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> JavaScript <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ol</span>&gt;</span>
</code></pre>
<h2 id="heading-forms">Forms</h2>
<p>The <code>&lt;form&gt;</code> tag is used to create a form in HTML. Forms are used to get user inputs. Here are some attributes associated with the <code>&lt;form&gt;</code> element:</p>
<ul>
<li><code>action</code> specifies where the form information goes when submitted.</li>
<li><code>target</code> specifies where to display the form's response.</li>
<li><code>autocomplete</code> can have a value of on or off. </li>
<li><code>novalidate</code> specifies that the form should not be validated.</li>
<li><code>method</code> specifies the HTTP method used when sending form data.</li>
<li><code>name</code>  specifies the name of the form.</li>
<li><code>required</code> specifies that an input element cannot be left empty.</li>
<li><code>autofocus</code> gives focus to the input elements when the page loads.</li>
<li><code>disabled</code> disables an input element so the user can longer interact with it.</li>
<li><code>placeholder</code> is used to give users a hint on what information is required for an input element.</li>
</ul>
<p>Here are other input elements associated with forms:</p>
<ul>
<li><code>&lt;textarea&gt;</code> for getting user text input with multiple lines.</li>
<li><code>&lt;select&gt;</code> specifies a list of options the user can choose from.</li>
<li><code>&lt;option&gt;</code> creates an option under the select element.</li>
<li><code>&lt;input&gt;</code> specifies an input field where the user can enter data. This has a <code>type</code> attribute that specifies what type of data the user can input.</li>
<li><code>&lt;button&gt;</code> creates a button.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/info_url/"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"firstName"</span>&gt;</span> First name: <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> 
           <span class="hljs-attr">name</span>=<span class="hljs-string">"firstName"</span> 
           <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"first name"</span> 
           <span class="hljs-attr">required</span>
    &gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"lastName"</span>&gt;</span> Last name: <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> 
           <span class="hljs-attr">name</span>=<span class="hljs-string">"lastName"</span> 
           <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"last name"</span> 
           <span class="hljs-attr">required</span>
    &gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"bio"</span>&gt;</span> Bio: <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"bio"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">textarea</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"age"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"15-18"</span>&gt;</span>15-18<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"19-25"</span>&gt;</span>19-25<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"26-30"</span>&gt;</span>26-30<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"31-36"</span>&gt;</span>31-36<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span>&gt;</span>

  <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<h2 id="heading-tables">Tables</h2>
<ul>
<li>The <code>&lt;table&gt;</code> tag defines a HTML table.</li>
<li><code>&lt;thead&gt;</code> specifies information for each column in a table.</li>
<li><code>&lt;tbody&gt;</code> specifies the body or content of the table.</li>
<li><code>&lt;tfoot&gt;</code> specifies the footer information of the table.</li>
<li><code>&lt;tr&gt;</code> denotes a row in the table.</li>
<li><code>&lt;td&gt;</code> denotes a single cell in the table.</li>
<li><code>&lt;th&gt;</code> denotes the value column's heading.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">thead</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span> Course <span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span> Progress <span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">thead</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span> HTML <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span> 90% <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span> CSS <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span> 80% <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">tfoot</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span> JavaScript <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span> 95% <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">tfoot</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
</code></pre>
<h2 id="heading-tags-introduced-in-html5">Tags introduced in HTML5</h2>
<p>Here are some tags introduced in HTML5:</p>
<ul>
<li><code>&lt;header&gt;</code> specifies the webpage header</li>
<li><code>&lt;footer&gt;</code> specifies the webpage footer. </li>
<li><code>&lt;main&gt;</code> specifies a main content section.</li>
<li><code>&lt;article&gt;</code> specifies an article's section, usually for content that can stand alone on the webpage.</li>
<li><code>&lt;section&gt;</code> is used to create separate sections.</li>
<li><code>&lt;aside&gt;</code> is usually used to when placing items in a sidebar.</li>
<li><code>&lt;time&gt;</code> is used for formatting date and time.</li>
<li><code>&lt;figure&gt;</code> is used for figures like charts.</li>
<li><code>&lt;figcaption&gt;</code> denotes a description of a figure.</li>
<li><code>&lt;nav&gt;</code> is used to nest navigation links.</li>
<li><code>&lt;meter&gt;</code> is used to measure data within a range.</li>
<li><code>&lt;progress&gt;</code> is used as a progress bar.</li>
<li><code>&lt;dialog&gt;</code> is used to create a dialog box.</li>
<li><code>&lt;audio&gt;</code> is used to embed an audio file in the web page.</li>
<li><code>&lt;video&gt;</code> is used to embed video.</li>
</ul>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Welcome <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span> Hello World! <span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Services<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>About us<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">article</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> An article about us <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Article content <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">aside</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> It's sunny today <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">aside</span>&gt;</span>

  <span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>

  Progress: <span class="hljs-tag">&lt;<span class="hljs-name">progress</span> <span class="hljs-attr">min</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">max</span>=<span class="hljs-string">"100"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"50"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">progress</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">footer</span>&gt;</span> Copyright 2022-2099. All Rights Reserved. <span class="hljs-tag">&lt;/<span class="hljs-name">footer</span>&gt;</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we have seen a lot of HTML tags, elements, and attributes commonly used by developers. This is not all there is, but should serve as a good reference resource.</p>
<p>I hope you found this helpful. Thank you for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ SQL Commands Cheat Sheet – How to Learn SQL in 10 Minutes ]]>
                </title>
                <description>
                    <![CDATA[ I’m an AI researcher, so one of the main things I deal with is data. A lot of it. With more than 2.5 exabytes of data generated every day, it comes as no surprise that this data needs to be stored somewhere where we can access it when we need ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-sql-in-10-minutes/</link>
                <guid isPermaLink="false">66d45f39052ad259f07e4aea</guid>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MySQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jason ]]>
                </dc:creator>
                <pubDate>Tue, 23 Nov 2021 15:36:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/11/sql-in-10-min-image.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I’m an AI researcher, so one of the main things I deal with is data. A <em>lot</em> of it.</p>
<p>With more than <a target="_blank" href="https://www.socialmediatoday.com/news/how-much-data-is-generated-every-minute-infographic-1/525692/">2.5 exabytes of data generated <em>every day</em></a>, it comes as no surprise that this data needs to be stored somewhere where we can access it when we need it.</p>
<p>This article will walk you through a hackable cheatsheet to get you up and running with SQL quickly.</p>
<h2 id="heading-what-is-sql">What is SQL?</h2>
<p>SQL stands for Structured Query Language. It is a language for relational database management systems. SQL is used today to store, retrieve, and manipulate data within relational databases.</p>
<p>Here’s what a basic relational database looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745433576314/ef41d0e6-7187-4856-927f-c1b899e3b73b.png" alt="Source: https://assets-global.website-files.com/5debb9b4f88fbc3f702d579e/5e3c1a71724a38245aa43b02_99bf70d46cc247be878de9d3a88f0c44.png" class="image--center mx-auto" width="773" height="367" loading="lazy"></p>
<p>Using SQL, we can interact with the database by writing <em>queries.</em></p>
<p>Here’s what an example query looks like:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> customers;
</code></pre>
<p>Using this <code>SELECT</code> statement, the query selects <em>all</em> the data from all the columns in the customer’s table and returns data like so:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/image-55.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Source: Database Guide</em></p>
<p>The asterisk wildcard character (*) refers to “<em>all</em>” and selects <em>all</em> the rows and columns. We can replace it with specific column names instead — here only those columns will be returned by the query</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> FirstName, LastName <span class="hljs-keyword">FROM</span> customers;
</code></pre>
<p>Adding a <code>WHERE</code> clause allows you to filter what gets returned:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> customers <span class="hljs-keyword">WHERE</span> age &gt;= <span class="hljs-number">30</span> <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> age <span class="hljs-keyword">ASC</span>;
</code></pre>
<p>This query returns all data from the products table with an <em>age</em> value of greater than 30.</p>
<p>The use of <code>ORDER BY</code> keyword just means the results will be ordered using the age column from the lowest value to the highest</p>
<p>Using the <code>INSERT INTO</code> statement, we can add new data to a table. Here’s a basic example adding a new user to the customers table:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> customers(FirstName, LastName, address, email)
<span class="hljs-keyword">VALUES</span> (<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'McLaren Vale, South Australia'</span>, <span class="hljs-string">'test@fakeGmail.com'</span>);
</code></pre>
<p>Of course, these examples demonstrate only a very small selection of what the SQL language can do. We'll learn more about it in this guide.</p>
<h2 id="heading-why-learn-sql">Why Learn SQL?</h2>
<p>We live in the age of Big Data, where data is used extensively to find insights and inform strategy, marketing, advertising and a plethora of other operations.</p>
<p>Big businesses like Google, Amazon, AirBnb utilize large, relational databases as a basis of improving customer experience. Understanding SQL is a great skill to have not only for data scientists and analysts but for everyone.</p>
<p><em>How do you think that you suddenly got a Youtube ad on shoes when just a few minutes ago, you were Googling your favourite shoes? That’s SQL (or a form of SQL) at work!</em></p>
<h2 id="heading-sql-vs-mysql">SQL vs MySQL</h2>
<p>Before we move on, I just want to clarify an often-confused topic — the difference between SQL and MySQL. As it turns out, they <em>aren’t</em> the same thing!</p>
<p>SQL is a language, while MySQL is a system to implement SQL.</p>
<p><strong>SQL</strong> outlines syntax that allows you to write queries that manage relational databases.</p>
<p><strong>MySQL</strong> is a database <em>system</em> that runs on a server. It allows you to write queries using SQL syntax to manage MySQL databases.</p>
<p>In addition to MySQL, there are other systems that implement SQL. Some of the more popular ones include:</p>
<ul>
<li><p>SQLite</p>
</li>
<li><p>Oracle Database</p>
</li>
<li><p>PostgreSQL</p>
</li>
<li><p>Microsoft SQL Server</p>
</li>
</ul>
<h2 id="heading-how-to-install-mysql">How to Install MySQL</h2>
<p>For most cases, MySQL is the preferred choice for a database management system. Many popular Content Management Systems (like Wordpress) use MySQL by default, so using MySQL to manage those applications can be a good idea.</p>
<p>In order to use MySQL, you’ll need to install it on your system:</p>
<h3 id="heading-install-mysql-on-windows">Install MySQL on Windows</h3>
<p>The recommended way to install MySQL on Windows is by using the MSI installer from the <a target="_blank" href="https://dev.mysql.com/doc/mysql-installer/en/mysql-installer.html">MySQL website</a>.</p>
<p><a target="_blank" href="https://www.liquidweb.com/kb/install-mysql-windows/">This resource will guide you with the installation process.</a></p>
<h3 id="heading-install-mysql-on-macos">Install MySQL on macOS</h3>
<p>On macOS, installing MySQL also involves downloading an <a target="_blank" href="https://dev.mysql.com/doc/mysql-osx-excerpt/8.0/en/osx-installation-pkg.html">installer.</a></p>
<p><a target="_blank" href="https://dev.mysql.com/doc/mysql-osx-excerpt/5.7/en/osx-installation-pkg.html">This resource will guide you through the installation process.</a></p>
<h2 id="heading-how-to-use-mysql">How to Use MySQL</h2>
<p>With MySQL now installed on your system, I recommend that you use some sort of <em>SQL management application</em> to make managing your databases a much easier process.</p>
<p>There are lots of apps to choose from which largely do the same job, so it’s down to your own personal preference on which one to use:</p>
<ul>
<li><p><a target="_blank" href="https://www.mysql.com/products/workbench/">MySQL Workbench</a> developed by Oracle</p>
</li>
<li><p><a target="_blank" href="http://phpmyadmin.net/">phpMyAdmin</a> (operates in the web browser)</p>
</li>
<li><p><a target="_blank" href="https://www.heidisql.com/">HeidiSQL</a> <strong>(Recommended for Windows)</strong></p>
</li>
<li><p><a target="_blank" href="https://www.sequelpro.com/">Sequel Pro</a> <strong>(Recommended for macOS)</strong></p>
</li>
</ul>
<p>When you’re ready to start writing your own SQL queries, consider importing dummy data rather than creating your own database.</p>
<p>Here are some <a target="_blank" href="https://dev.mysql.com/doc/index-other.html">dummy databases</a> that are available for download free of charge.</p>
<h2 id="heading-sql-cheatsheet-the-icing-on-the-cake">SQL Cheatsheet – The Icing on the Cake</h2>
<h3 id="heading-sql-keywords">SQL Keywords</h3>
<p>Here you can find a collection of keywords used in SQL statements, a description, and where appropriate an example. Some of the more advanced keywords have their own dedicated section.</p>
<p>Where MySQL is mentioned next to an example, this means this example is only applicable to MySQL databases (as opposed to any other database system).</p>
<pre><code class="lang-sql">ADD <span class="hljs-comment">-- Adds a new column to an existing table</span>

ADD CONSTRAINT <span class="hljs-comment">-- Creates a new constraint on an existing table, which is used to specify rules for any data in the table.</span>

<span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-comment">-- Adds, deletes or edits columns in a table. It can also be used to add and delete constraints in a table, as per the above.</span>

<span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">COLUMN</span> <span class="hljs-comment">-- Changes the data type of a table’s column.</span>

<span class="hljs-keyword">ALL</span> <span class="hljs-comment">-- Returns true if all of the subquery values meet the passed condition.</span>

<span class="hljs-keyword">AND</span> <span class="hljs-comment">-- Used to join separate conditions within a WHERE clause.</span>

<span class="hljs-keyword">ANY</span> <span class="hljs-comment">-- Returns true if any of the subquery values meet the given condition.</span>

<span class="hljs-keyword">AS</span> <span class="hljs-comment">-- Renames a table or column with an alias value which only exists for the duration of the query.</span>

<span class="hljs-keyword">ASC</span> <span class="hljs-comment">-- Used with ORDER BY to return the data in ascending order.</span>

<span class="hljs-keyword">BETWEEN</span> <span class="hljs-comment">-- Selects values within the given range.</span>

<span class="hljs-keyword">CASE</span> <span class="hljs-comment">-- Changes query output depending on conditions.</span>

<span class="hljs-keyword">CHECK</span> <span class="hljs-comment">-- Adds a constraint that limits the value which can be added to a column.</span>

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> <span class="hljs-comment">-- Creates a new database.</span>

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-comment">-- Creates a new table. </span>

<span class="hljs-keyword">DEFAULT</span> <span class="hljs-comment">-- Sets a default value for a column</span>

<span class="hljs-keyword">DELETE</span> <span class="hljs-comment">-- Delete data from a table.</span>

<span class="hljs-keyword">DESC</span> <span class="hljs-comment">-- Used with ORDER BY to return the data in descending order.</span>

<span class="hljs-keyword">DROP</span> <span class="hljs-keyword">COLUMN</span> <span class="hljs-comment">-- Deletes a column from a table.</span>

<span class="hljs-keyword">DROP</span> <span class="hljs-keyword">DATABASE</span> <span class="hljs-comment">-- Deletes the entire database.</span>

<span class="hljs-keyword">DROP</span> DEAFULT <span class="hljs-comment">-- Removes a default value for a column.</span>

<span class="hljs-keyword">DROP</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-comment">-- Deletes a table from a database.</span>

<span class="hljs-keyword">EXISTS</span> <span class="hljs-comment">-- Checks for the existence of any record within the subquery, returning true if one or more records are returned.</span>

<span class="hljs-keyword">FROM</span> <span class="hljs-comment">-- Specifies which table to select or delete data from.</span>

<span class="hljs-keyword">IN</span> <span class="hljs-comment">--  Used alongside a WHERE clause as a shorthand for multiple OR conditions.</span>

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-comment">-- Adds new rows to a table.</span>

<span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-comment">-- Tests for empty (NULL) values.</span>

<span class="hljs-keyword">IS</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span> <span class="hljs-comment">-- The reverse of NULL. Tests for values that aren’t empty / NULL.</span>

<span class="hljs-keyword">LIKE</span> <span class="hljs-comment">-- Returns true if the operand value matches a pattern.</span>

<span class="hljs-keyword">NOT</span> <span class="hljs-comment">-- Returns true if a record DOESN’T meet the condition.</span>

<span class="hljs-keyword">OR</span> <span class="hljs-comment">-- Used alongside WHERE to include data when either condition is true.</span>

<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> <span class="hljs-comment">-- Used to sort the result data in ascending (default) or descending order through the use of ASC or DESC keywords.</span>

<span class="hljs-keyword">ROWNUM</span> <span class="hljs-comment">-- Returns results where the row number meets the passed condition.</span>

<span class="hljs-keyword">SELECT</span> <span class="hljs-comment">-- Used to select data from a database, which is then returned in a results set.</span>

<span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">DISTINCT</span> <span class="hljs-comment">-- Sames as SELECT, except duplicate values are excluded.</span>

<span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-comment">-- Copies data from one table and inserts it into another.</span>

<span class="hljs-keyword">SELECT</span> TOP <span class="hljs-comment">-- Allows you to return a set number of records to return from a table.</span>

<span class="hljs-keyword">SET</span> <span class="hljs-comment">-- Used alongside UPDATE to update existing data in a table.</span>

<span class="hljs-keyword">SOME</span> <span class="hljs-comment">-- Identical to ANY.</span>

TOP <span class="hljs-comment">-- Used alongside SELECT to return a set number of records from a table.</span>

<span class="hljs-keyword">TRUNCATE</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-comment">-- Similar to DROP, but instead of deleting the table and its data, this deletes only the data.</span>

<span class="hljs-keyword">UNION</span> <span class="hljs-comment">-- Combines the results from 2 or more SELECT statements and returns only distinct values.</span>

<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span> <span class="hljs-comment">-- The same as UNION, but includes duplicate values.</span>

<span class="hljs-keyword">UNIQUE</span> <span class="hljs-comment">-- This constraint ensures all values in a column are unique.</span>

<span class="hljs-keyword">UPDATE</span> <span class="hljs-comment">-- Updates existing data in a table.</span>

<span class="hljs-keyword">VALUES</span> <span class="hljs-comment">-- Used alongside the INSERT INTO keyword to add new values to a table.</span>

<span class="hljs-keyword">WHERE</span> <span class="hljs-comment">-- Filters results to only include data which meets the given condition.</span>
</code></pre>
<h3 id="heading-comments-in-sql">Comments in SQL</h3>
<p>Comments allow you to explain sections of your SQL statements, without being executed directly.</p>
<p>In SQL, there are 2 types of comments, single line and multiline.</p>
<h4 id="heading-single-line-comments-in-sql">Single Line Comments in SQL</h4>
<p>Single line comments start with ‘- -’. Any text after these 2 characters to the end of the line will be ignored.</p>
<pre><code class="lang-sql"><span class="hljs-comment">-- This part is ignored</span>

<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> customers;
</code></pre>
<h4 id="heading-multiline-comments-in-sql">Multiline Comments in SQL</h4>
<p>Multiline comments start with /* and end with */. They stretch across multiple lines until the closing characters have been found.</p>
<pre><code class="lang-json"><span class="hljs-comment">/*

This is a multiline comment.
It can span across multiple lines.

*/</span>

SELECT * FROM customers;

<span class="hljs-comment">/*

This is another comment. 
You can even put code within a comment to prevent its execution

SELECT * FROM icecreams;

*/</span>
</code></pre>
<h3 id="heading-data-types-in-mysql">Data Types in MySQL</h3>
<p>When creating a new table or editing an existing one, you must specify the type of data that each column accepts.</p>
<p><a target="_blank" href="https://www.datadriveninvestor.com/2020/05/04/could-machine-learning-and-nlp-have-predicted-oils-crash-the-answer-is-yes/">In this example</a>, data passed to the <code>id</code> column must be an int (integer), while the <code>FirstName</code> column has a <code>VARCHAR</code> data type with a maximum of 255 characters.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> customers(
<span class="hljs-keyword">id</span> <span class="hljs-built_in">int</span>,
FirstName <span class="hljs-built_in">varchar</span>(<span class="hljs-number">255</span>)
);
</code></pre>
<h4 id="heading-1-string-data-types">1. String Data Types</h4>
<pre><code class="lang-sql">CHAR(size) <span class="hljs-comment">-- Fixed length string which can contain letters, numbers and special characters. The size parameter sets the maximum string length, from 0 – 255 with a default of 1.</span>

VARCHAR(size) <span class="hljs-comment">-- Variable length string similar to CHAR(), but with a maximum string length range from 0 to 65535.</span>

BINARY(size) <span class="hljs-comment">-- Similar to CHAR() but stores binary byte strings.</span>

VARBINARY(size) <span class="hljs-comment">-- Similar to VARCHAR() but for binary byte strings.</span>

TINYBLOB <span class="hljs-comment">-- Holds Binary Large Objects (BLOBs) with a max length of 255 bytes.</span>

TINYTEXT <span class="hljs-comment">-- Holds a string with a maximum length of 255 characters. Use VARCHAR() instead, as it’s fetched much faster.</span>

TEXT(size) <span class="hljs-comment">-- Holds a string with a maximum length of 65535 bytes. Again, better to use VARCHAR().</span>

BLOB(size) <span class="hljs-comment">-- Holds Binary Large Objects (BLOBs) with a max length of 65535 bytes.</span>

MEDIUMTEXT <span class="hljs-comment">-- Holds a string with a maximum length of 16,777,215 characters.</span>

MEDIUMBLOB <span class="hljs-comment">-- Holds Binary Large Objects (BLOBs) with a max length of 16,777,215 bytes.</span>

LONGTEXT <span class="hljs-comment">-- Holds a string with a maximum length of 4,294,967,295 characters.</span>

LONGBLOB <span class="hljs-comment">-- Holds Binary Large Objects (BLOBs) with a max length of 4,294,967,295 bytes.</span>

ENUM(a, b, c, etc…) <span class="hljs-comment">-- A string object that only has one value, which is chosen from a list of values which you define, up to a maximum of 65535 values. If a value is added which isn’t on this list, it’s replaced with a blank value instead.</span>

<span class="hljs-keyword">SET</span>(a, b, c, etc…) <span class="hljs-comment">-- A string object that can have 0 or more values, which is chosen from a list of values which you define, up to a maximum of 64 values.</span>
</code></pre>
<h4 id="heading-2-numeric-data-types">2. Numeric Data Types</h4>
<pre><code class="lang-sql">BIT(size) <span class="hljs-comment">-- A bit-value type with a default of 1. The allowed number of bits in a value is set via the size parameter, which can hold values from 1 to 64.</span>

TINYINT(size) <span class="hljs-comment">-- A very small integer with a signed range of -128 to 127, and an unsigned range of 0 to 255. Here, the size parameter specifies the maximum allowed display width, which is 255.</span>

BOOL <span class="hljs-comment">-- Essentially a quick way of setting the column to TINYINT with a size of 1. 0 is considered false, whilst 1 is considered true.</span>

BOOLEAN    <span class="hljs-comment">-- Same as BOOL.</span>

SMALLINT(size) <span class="hljs-comment">-- A small integer with a signed range of -32768 to 32767, and an unsigned range from 0 to 65535. Here, the size parameter specifies the maximum allowed display width, which is 255.</span>

MEDIUMINT(size) <span class="hljs-comment">-- A medium integer with a signed range of -8388608 to 8388607, and an unsigned range from 0 to 16777215. Here, the size parameter specifies the maximum allowed display width, which is 255.</span>

INT(size) <span class="hljs-comment">-- A medium integer with a signed range of -2147483648 to 2147483647, and an unsigned range from 0 to 4294967295. Here, the size parameter specifies the maximum allowed display width, which is 255.</span>

INTEGER(size) <span class="hljs-comment">-- Same as INT.</span>

BIGINT(size) <span class="hljs-comment">-- A medium integer with a signed range of -9223372036854775808 to 9223372036854775807, and an unsigned range from 0 to 18446744073709551615. Here, the size parameter specifies the maximum allowed display width, which is 255.</span>

FLOAT(p) <span class="hljs-comment">-- A floating point number value. If the precision (p) parameter is between 0 to 24, then the data type is set to FLOAT(), whilst if it's from 25 to 53, the data type is set to DOUBLE(). This behaviour is to make the storage of values more efficient.</span>

DOUBLE(size, d) <span class="hljs-comment">-- A floating point number value where the total digits are set by the size parameter, and the number of digits after the decimal point is set by the d parameter.</span>

DECIMAL(size, d) <span class="hljs-comment">-- An exact fixed point number where the total number of digits is set by the size parameters, and the total number of digits after the decimal point is set by the d parameter.</span>

DEC(size, d) <span class="hljs-comment">-- Same as DECIMAL.</span>
</code></pre>
<h4 id="heading-3-datetime-data-types">3. Date/Time Data Types</h4>
<pre><code class="lang-sql">DATE <span class="hljs-comment">-- A simple date in YYYY-MM–DD format, with a supported range from ‘1000-01-01’ to ‘9999-12-31’.</span>

DATETIME(fsp) <span class="hljs-comment">-- A date time in YYYY-MM-DD hh:mm:ss format, with a supported range from ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’. By adding DEFAULT and ON UPDATE to the column definition, it automatically sets to the current date/time.</span>

TIMESTAMP(fsp) <span class="hljs-comment">-- A Unix Timestamp, which is a value relative to the number of seconds since the Unix epoch (‘1970-01-01 00:00:00’ UTC). This has a supported range from ‘1970-01-01 00:00:01’ UTC to ‘2038-01-09 03:14:07’ UTC.</span>
By adding DEFAULT CURRENT_TIMESTAMP and ON <span class="hljs-keyword">UPDATE</span> <span class="hljs-keyword">CURRENT</span> <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">to</span> the <span class="hljs-keyword">column</span> definition, it automatically <span class="hljs-keyword">sets</span> <span class="hljs-keyword">to</span> <span class="hljs-keyword">current</span> <span class="hljs-built_in">date</span>/time.

<span class="hljs-built_in">TIME</span>(fsp) <span class="hljs-comment">-- A time in hh:mm:ss format, with a supported range from ‘-838:59:59’ to ‘838:59:59’.</span>

<span class="hljs-keyword">YEAR</span> <span class="hljs-comment">-- A year, with a supported range of ‘1901’ to ‘2155’.</span>
</code></pre>
<h3 id="heading-sql-operators">SQL Operators</h3>
<h4 id="heading-1-arithmetic-operators-in-sql">1. Arithmetic Operators in SQL</h4>
<pre><code class="lang-sql">+ <span class="hljs-comment">-- Add</span>
– <span class="hljs-comment">-- Subtract</span>
* <span class="hljs-comment">-- Multiply</span>
/ <span class="hljs-comment">-- Divide</span>
% <span class="hljs-comment">-- Modulus</span>
</code></pre>
<h4 id="heading-2-bitwise-operators-in-sql">2. Bitwise Operators in SQL</h4>
<pre><code class="lang-sql">&amp; <span class="hljs-comment">-- Bitwise AND</span>
| <span class="hljs-comment">-- Bitwise OR</span>
^<span class="hljs-comment">-- Bitwise XOR</span>
</code></pre>
<h4 id="heading-3-comparison-operators-in-sql">3. Comparison Operators in SQL</h4>
<pre><code class="lang-sql">= <span class="hljs-comment">-- Equal to</span>
&gt; <span class="hljs-comment">-- Greater than</span>
&lt; <span class="hljs-comment">-- Less than</span>
&gt;= <span class="hljs-comment">-- Greater than or equal to</span>
&lt;= <span class="hljs-comment">-- Less than or equal to</span>
&lt;&gt; <span class="hljs-comment">-- Not equal to</span>
</code></pre>
<h4 id="heading-4-compound-operators-in-sql">4. Compound Operators in SQL</h4>
<pre><code class="lang-sql">+= <span class="hljs-comment">-- Add equals</span>
-= <span class="hljs-comment">-- Subtract equals</span>
*= <span class="hljs-comment">-- Multiply equals</span>
/= <span class="hljs-comment">-- Divide equals</span>
%= <span class="hljs-comment">-- Modulo equals</span>
&amp;= <span class="hljs-comment">-- Bitwise AND equals</span>
^-= <span class="hljs-comment">-- Bitwise exclusive equals</span>
|*= <span class="hljs-comment">-- Bitwise OR equals</span>
</code></pre>
<h3 id="heading-sql-functions">SQL Functions</h3>
<h4 id="heading-1-string-functions-in-sql">1. String Functions in SQL</h4>
<pre><code class="lang-sql">ASCII <span class="hljs-comment">-- Returns the equivalent ASCII value for a specific character.</span>

CHAR_LENGTH <span class="hljs-comment">-- Returns the character length of a string.</span>

CHARACTER_LENGTH <span class="hljs-comment">-- Same as CHAR_LENGTH.</span>

CONCAT <span class="hljs-comment">-- Adds expressions together, with a minimum of 2.</span>

CONCAT_WS <span class="hljs-comment">-- Adds expressions together, but with a separator between each value.</span>

FIELD <span class="hljs-comment">-- Returns an index value relative to the position of a value within a list of values.</span>

FIND IN <span class="hljs-keyword">SET</span> <span class="hljs-comment">-- Returns the position of a string in a list of strings.</span>

<span class="hljs-keyword">FORMAT</span> <span class="hljs-comment">-- When passed a number, returns that number formatted to include commas (eg 3,400,000).</span>

<span class="hljs-keyword">INSERT</span> <span class="hljs-comment">-- Allows you to insert one string into another at a certain point, for a certain number of characters.</span>

<span class="hljs-keyword">INSTR</span> <span class="hljs-comment">-- Returns the position of the first time one string appears within another.</span>

<span class="hljs-keyword">LCASE</span> <span class="hljs-comment">-- Converts a string to lowercase.</span>

<span class="hljs-keyword">LEFT</span> <span class="hljs-comment">-- Starting from the left, extracts the given number of characters from a string and returns them as another.</span>

<span class="hljs-keyword">LENGTH</span> <span class="hljs-comment">-- Returns the length of a string, but in bytes.</span>

<span class="hljs-keyword">LOCATE</span> <span class="hljs-comment">-- Returns the first occurrence of one string within another,</span>

<span class="hljs-keyword">LOWER</span> <span class="hljs-comment">-- Same as LCASE.</span>

<span class="hljs-keyword">LPAD</span> <span class="hljs-comment">-- Left pads one string with another, to a specific length.</span>

<span class="hljs-keyword">LTRIM</span> <span class="hljs-comment">-- Removes any leading spaces from the given string.</span>

<span class="hljs-keyword">MID</span> <span class="hljs-comment">-- Extracts one string from another, starting from any position.</span>

<span class="hljs-keyword">POSITION</span> <span class="hljs-comment">-- Returns the position of the first time one substring appears within another.</span>

<span class="hljs-keyword">REPEAT</span> <span class="hljs-comment">-- Allows you to repeat a string</span>

<span class="hljs-keyword">REPLACE</span> <span class="hljs-comment">-- Allows you to replace any instances of a substring within a string, with a new substring.</span>

<span class="hljs-keyword">REVERSE</span>    <span class="hljs-comment">-- Reverses the string.</span>

<span class="hljs-keyword">RIGHT</span> <span class="hljs-comment">-- Starting from the right, extracts the given number of characters from a string and returns them as another.</span>

RPAD <span class="hljs-comment">-- Right pads one string with another, to a specific length.</span>

<span class="hljs-keyword">RTRIM</span> <span class="hljs-comment">-- Removes any trailing spaces from the given string.</span>

<span class="hljs-keyword">SPACE</span> <span class="hljs-comment">-- Returns a string full of spaces equal to the amount you pass it.</span>

<span class="hljs-keyword">STRCMP</span> <span class="hljs-comment">-- Compares 2 strings for differences</span>

<span class="hljs-keyword">SUBSTR</span> <span class="hljs-comment">-- Extracts one substring from another, starting from any position.</span>

<span class="hljs-keyword">SUBSTRING</span> <span class="hljs-comment">-- Same as SUBSTR</span>

SUBSTRING_INDEX    <span class="hljs-comment">-- Returns a substring from a string before the passed substring is found the number of times equals to the passed number.</span>

<span class="hljs-keyword">TRIM</span> <span class="hljs-comment">--    Removes trailing and leading spaces from the given string. Same as if you were to run LTRIM and RTRIM together.</span>

<span class="hljs-keyword">UCASE</span> <span class="hljs-comment">-- Converts a string to uppercase.</span>

<span class="hljs-keyword">UPPER</span> <span class="hljs-comment">-- Same as UCASE.</span>
</code></pre>
<h4 id="heading-2-numeric-functions-in-sql">2. Numeric Functions in SQL</h4>
<pre><code class="lang-sql">ABS <span class="hljs-comment">-- Returns the absolute value of the given number.</span>

ACOS <span class="hljs-comment">-- Returns the arc cosine of the given number.</span>

ASIN <span class="hljs-comment">-- Returns the arc sine of the given number.</span>

ATAN <span class="hljs-comment">-- Returns the arc tangent of one or 2 given numbers.</span>

ATAN2 <span class="hljs-comment">-- Returns the arc tangent of 2 given numbers.</span>

AVG <span class="hljs-comment">-- Returns the average value of the given expression.</span>

CEIL <span class="hljs-comment">-- Returns the closest whole number (integer) upwards from a given decimal point number.</span>

CEILING <span class="hljs-comment">-- Same as CEIL.</span>

COS <span class="hljs-comment">-- Returns the cosine of a given number.</span>

COT <span class="hljs-comment">-- Returns the cotangent of a given number.</span>

COUNT <span class="hljs-comment">-- Returns the amount of records that are returned by a SELECT query.</span>

DEGREES <span class="hljs-comment">-- Converts a radians value to degrees.</span>

DIV <span class="hljs-comment">-- Allows you to divide integers.</span>

EXP <span class="hljs-comment">-- Returns e to the power of the given number.</span>

FLOOR <span class="hljs-comment">-- Returns the closest whole number (integer) downwards from a given decimal point number.</span>

GREATEST <span class="hljs-comment">-- Returns the highest value in a list of arguments.</span>

LEAST <span class="hljs-comment">-- Returns the smallest value in a list of arguments.</span>

LN <span class="hljs-comment">-- Returns the natural logarithm of the given number.</span>

LOG <span class="hljs-comment">-- Returns the natural logarithm of the given number, or the logarithm of the given number to the given base.</span>

LOG10 <span class="hljs-comment">-- Does the same as LOG, but to base 10.</span>

LOG2 <span class="hljs-comment">-- Does the same as LOG, but to base 2.</span>

MAX <span class="hljs-comment">-- Returns the highest value from a set of values.</span>

MIN <span class="hljs-comment">-- Returns the lowest value from a set of values.</span>

MOD <span class="hljs-comment">-- Returns the remainder of the given number divided by the other given number.</span>

PI <span class="hljs-comment">-- Returns PI.</span>

POW <span class="hljs-comment">-- Returns the value of the given number raised to the power of the other given number.</span>

POWER <span class="hljs-comment">-- Same as POW.</span>

RADIANS <span class="hljs-comment">-- Converts a degrees value to radians.</span>

RAND <span class="hljs-comment">-- Returns a random number.</span>

ROUND <span class="hljs-comment">-- Rounds the given number to the given amount of decimal places.</span>

SIGN <span class="hljs-comment">-- Returns the sign of the given number.</span>

SIN <span class="hljs-comment">-- Returns the sine of the given number.</span>

SQRT <span class="hljs-comment">-- Returns the square root of the given number.</span>

SUM <span class="hljs-comment">-- Returns the value of the given set of values combined.</span>

TAN <span class="hljs-comment">-- Returns the tangent of the given number.</span>

<span class="hljs-keyword">TRUNCATE</span> <span class="hljs-comment">-- Returns a number truncated to the given number of decimal places.</span>
</code></pre>
<h4 id="heading-3-date-functions-in-sql">3. Date Functions in SQL</h4>
<pre><code class="lang-sql">ADDDATE <span class="hljs-comment">-- Adds a date interval (eg: 10 DAY) to a date (eg: 20/01/20) and returns the result (eg: 20/01/30).</span>

ADDTIME <span class="hljs-comment">-- Adds a time interval (eg: 02:00) to a time or datetime (05:00) and returns the result (07:00).</span>

CURDATE <span class="hljs-comment">-- Gets the current date.</span>

CURRENT_DATE <span class="hljs-comment">-- Same as CURDATE.</span>

CURRENT_TIME <span class="hljs-comment">-- Gest the current time.</span>

CURRENT_TIMESTAMP <span class="hljs-comment">-- Gets the current date and time.</span>

CURTIME <span class="hljs-comment">-- Same as CURRENT_TIME.</span>

DATE <span class="hljs-comment">-- Extracts the date from a datetime expression.</span>

DATEDIFF <span class="hljs-comment">-- Returns the number of days between the 2 given dates.</span>

DATE_ADD <span class="hljs-comment">-- Same as ADDDATE.</span>

DATE_FORMAT <span class="hljs-comment">-- Formats the date to the given pattern.</span>

DATE_SUB <span class="hljs-comment">-- Subtracts a date interval (eg: 10 DAY) to a date (eg: 20/01/20) and returns the result (eg: 20/01/10).</span>

DAY <span class="hljs-comment">-- Returns the day for the given date.</span>

DAYNAME <span class="hljs-comment">-- Returns the weekday name for the given date.</span>

DAYOFWEEK <span class="hljs-comment">-- Returns the index for the weekday for the given date.</span>

DAYOFYEAR <span class="hljs-comment">-- Returns the day of the year for the given date.</span>

EXTRACT <span class="hljs-comment">-- Extracts from the date the given part (eg MONTH for 20/01/20 = 01).</span>

FROM DAYS <span class="hljs-comment">-- Returns the date from the given numeric date value.</span>

HOUR <span class="hljs-comment">-- Returns the hour from the given date.</span>

LAST DAY <span class="hljs-comment">-- Gets the last day of the month for the given date.</span>

LOCALTIME <span class="hljs-comment">-- Gets the current local date and time.</span>

LOCALTIMESTAMP <span class="hljs-comment">-- Same as LOCALTIME.</span>

MAKEDATE <span class="hljs-comment">-- Creates a date and returns it, based on the given year and number of days values.</span>

MAKETIME <span class="hljs-comment">-- Creates a time and returns it, based on the given hour, minute and second values.</span>

MICROSECOND <span class="hljs-comment">-- Returns the microsecond of a given time or datetime.</span>

MINUTE <span class="hljs-comment">-- Returns the minute of the given time or datetime.</span>

MONTH <span class="hljs-comment">-- Returns the month of the given date.</span>

MONTHNAME <span class="hljs-comment">-- Returns the name of the month of the given date.</span>

NOW <span class="hljs-comment">-- Same as LOCALTIME.</span>

PERIOD_ADD <span class="hljs-comment">-- Adds the given number of months to the given period.</span>

PERIOD_DIFF <span class="hljs-comment">-- Returns the difference between 2 given periods.</span>

QUARTER <span class="hljs-comment">-- Returns the year quarter for the given date.</span>

SECOND <span class="hljs-comment">-- Returns the second of a given time or datetime.</span>

SEC_TO_TIME <span class="hljs-comment">-- Returns a time based on the given seconds.</span>

STR_TO_DATE <span class="hljs-comment">-- Creates a date and returns it based on the given string and format.</span>

SUBDATE <span class="hljs-comment">-- Same as DATE_SUB.</span>

SUBTIME <span class="hljs-comment">-- Subtracts a time interval (eg: 02:00) to a time or datetime (05:00) and returns the result (03:00).</span>

SYSDATE <span class="hljs-comment">-- Same as LOCALTIME.</span>

TIME <span class="hljs-comment">-- Returns the time from a given time or datetime.</span>

TIME_FORMAT <span class="hljs-comment">-- Returns the given time in the given format.</span>

TIME_TO_SEC <span class="hljs-comment">-- Converts and returns a time into seconds.</span>

TIMEDIFF <span class="hljs-comment">-- Returns the difference between 2 given time/datetime expressions.</span>

TIMESTAMP <span class="hljs-comment">-- Returns the datetime value of the given date or datetime.</span>

TO_DAYS <span class="hljs-comment">-- Returns the total number of days that have passed from ‘00-00-0000’ to the given date.</span>

WEEK <span class="hljs-comment">-- Returns the week number for the given date.</span>

WEEKDAY <span class="hljs-comment">-- Returns the weekday number for the given date.</span>

WEEKOFYEAR <span class="hljs-comment">-- Returns the week number for the given date.</span>

YEAR <span class="hljs-comment">-- Returns the year from the given date.</span>

YEARWEEK <span class="hljs-comment">-- Returns the year and week number for the given date.</span>
</code></pre>
<h4 id="heading-4-miscellaneous-functions-in-sql">4. Miscellaneous Functions in SQL</h4>
<pre><code class="lang-sql">BIN <span class="hljs-comment">-- Returns the given number in binary.</span>

BINARY <span class="hljs-comment">-- Returns the given value as a binary string.</span>

CAST <span class="hljs-comment">-- Converst one type into another.</span>

COALESCE <span class="hljs-comment">-- From a list of values, returns the first non-null value.</span>

CONNECTION_ID <span class="hljs-comment">-- For the current connection, returns the unique connection ID.</span>

CONV <span class="hljs-comment">-- Converts the given number from one numeric base system into another.</span>

CONVERT <span class="hljs-comment">-- Converts the given value into the given datatype or character set.</span>

CURRENT_USER <span class="hljs-comment">-- Returns the user and hostname which was used to authenticate with the server.</span>

DATABASE <span class="hljs-comment">-- Gets the name of the current database.</span>

GROUP BY <span class="hljs-comment">-- Used alongside aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the results.</span>

HAVING <span class="hljs-comment">-- Used in the place of WHERE with aggregate functions.</span>

IF <span class="hljs-comment">-- If the condition is true it returns a value, otherwise it returns another value.</span>

IFNULL <span class="hljs-comment">-- If the given expression equates to null, it returns the given value.</span>

ISNULL <span class="hljs-comment">-- If the expression is null, it returns 1, otherwise returns 0.</span>

LAST_INSERT_ID <span class="hljs-comment">-- For the last row which was added or updated in a table, returns the auto increment ID.</span>

NULLIF <span class="hljs-comment">-- Compares the 2 given expressions. If they are equal, NULL is returned, otherwise the first expression is returned.</span>

SESSION_USER <span class="hljs-comment">-- Returns the current user and hostnames.</span>

SYSTEM_USER <span class="hljs-comment">-- Same as SESSION_USER.</span>

USER <span class="hljs-comment">-- Same as SESSION_USER.</span>

VERSION <span class="hljs-comment">-- Returns the current version of the MySQL powering the database.</span>
</code></pre>
<h3 id="heading-wildcard-characters-in-sql">Wildcard Characters in SQL</h3>
<p>In SQL, Wildcards are special characters used with the <code>LIKE</code> and <code>NOT LIKE</code> keywords. This allows us to search for data with sophisticated patterns rather efficiently.</p>
<pre><code class="lang-sql">% <span class="hljs-comment">-- Equates to zero or more characters.</span>
<span class="hljs-comment">-- Example: Find all customers with surnames ending in ‘ory’.</span>
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> customers
<span class="hljs-keyword">WHERE</span> surname <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'%ory'</span>;

_ <span class="hljs-comment">-- Equates to any single character.</span>
<span class="hljs-comment">-- Example: Find all customers living in cities beginning with any 3 characters, followed by ‘vale’.</span>
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> customers
<span class="hljs-keyword">WHERE</span> city <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'_ _ _vale'</span>;

[charlist] <span class="hljs-comment">-- Equates to any single character in the list.</span>
<span class="hljs-comment">-- Example: Find all customers with first names beginning with J, K or T.</span>
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> customers
<span class="hljs-keyword">WHERE</span> first_name <span class="hljs-keyword">LIKE</span> <span class="hljs-string">'[jkt]%'</span>;
</code></pre>
<h3 id="heading-sql-keys">SQL Keys</h3>
<p>In relational databases, there is a concept of <em>primary</em> and <em>foreign</em> keys. In SQL tables, these are included as constraints, where a table can have a primary key, a foreign key, or both.</p>
<h4 id="heading-1-primary-keys-in-sql">1. Primary Keys in SQL</h4>
<p>A primary lets each record in a table be uniquely identified. You can only have one primary key per table, and you can assign this constraint to any single or combination of columns. However, this means each value within this column(s) needs to be unique.</p>
<p>Typically in a table, the ID column is a primary key, and is usually paired with the <code>AUTO_INCREMENT</code> keyword. This means the value increases automatically as and when new records are created.</p>
<h4 id="heading-example-mysql">Example (MySQL)</h4>
<p>Create a new table and set the primary key to the ID column.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> customers (
<span class="hljs-keyword">id</span> <span class="hljs-built_in">int</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span> AUTO_INCREMENT,
FirstName <span class="hljs-built_in">varchar</span>(<span class="hljs-number">255</span>),
<span class="hljs-keyword">Last</span> <span class="hljs-keyword">Name</span> <span class="hljs-built_in">varchar</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
address <span class="hljs-built_in">varchar</span>(<span class="hljs-number">255</span>),
email <span class="hljs-built_in">varchar</span>(<span class="hljs-number">255</span>),
PRIMARY <span class="hljs-keyword">KEY</span> (<span class="hljs-keyword">id</span>)
);
</code></pre>
<h4 id="heading-2-foreign-keys-in-sql">2. Foreign Keys in SQL</h4>
<p>You can apply a foreign key to one column or many. You use it to <em>link</em> 2 tables together in a relational database.</p>
<p>The table containing the foreign key is called the <em>child</em> key,</p>
<p>The table containing the referenced (or candidate) key is called the <em>parent</em> table.</p>
<p>This essentially means that the column data is shared between 2 tables, because a foreign key also prevents invalid data from being inserted which isn’t also present in the parent table.</p>
<h4 id="heading-example-mysql-1">Example (MySQL)</h4>
<p>Create a new table and turn any column that references IDs in other tables into foreign keys.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> orders (
<span class="hljs-keyword">id</span> <span class="hljs-built_in">int</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
user_id <span class="hljs-built_in">int</span>,
product_id <span class="hljs-built_in">int</span>,
PRIMARY <span class="hljs-keyword">KEY</span> (<span class="hljs-keyword">id</span>),
<span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (user_id) <span class="hljs-keyword">REFERENCES</span> <span class="hljs-keyword">users</span>(<span class="hljs-keyword">id</span>),
<span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (product_id) <span class="hljs-keyword">REFERENCES</span> products(<span class="hljs-keyword">id</span>)
);
</code></pre>
<h3 id="heading-indexes-in-sql">Indexes in SQL</h3>
<p>Indexes are attributes that can be assigned to columns that are frequently searched against to make data retrieval a quicker and more efficient process.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> <span class="hljs-comment">-- Creates an index named ‘idx_test’ on the first_name and surname columns of the users table. In this instance, duplicate values are allowed.</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_test
<span class="hljs-keyword">ON</span> <span class="hljs-keyword">users</span> (first_name, surname);
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">UNIQUE</span> <span class="hljs-keyword">INDEX</span> <span class="hljs-comment">-- The same as the above, but no duplicate values.</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">UNIQUE</span> <span class="hljs-keyword">INDEX</span> idx_test
<span class="hljs-keyword">ON</span> <span class="hljs-keyword">users</span> (first_name, surname);
<span class="hljs-keyword">DROP</span> <span class="hljs-keyword">INDEX</span> <span class="hljs-comment">-- Removes an index.</span>
<span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-keyword">users</span>
<span class="hljs-keyword">DROP</span> <span class="hljs-keyword">INDEX</span> idx_test;
</code></pre>
<h3 id="heading-sql-joins">SQL Joins</h3>
<p>In SQL, a <code>JOIN</code> clause is used to return a result which combines data from multiple tables, based on a common column which is featured in both of them.</p>
<p>There are a number of different joins available for you to use:</p>
<ul>
<li><p><strong>Inner Join (Default):</strong> Returns any records which have matching values in both tables.</p>
</li>
<li><p><strong>Left Join:</strong> Returns all of the records from the first table, along with any matching records from the second table.</p>
</li>
<li><p><strong>Right Join:</strong> Returns all of the records from the second table, along with any matching records from the first.</p>
</li>
<li><p><strong>Full Join:</strong> Returns all records from both tables when there is a match.</p>
</li>
</ul>
<p>A common way of visualising how joins work is like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/image-56.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://websitesetup.org/sql-cheat-sheet/"><em>Source</em></a><em>: Website Setup</em></p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> orders.id, users.FirstName, users.Surname, products.name <span class="hljs-keyword">as</span> ‘product <span class="hljs-keyword">name</span>’
<span class="hljs-keyword">FROM</span> orders
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">on</span> orders.user_id = users.id
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> products <span class="hljs-keyword">on</span> orders.product_id = products.id;
</code></pre>
<h3 id="heading-views-in-sql">Views in SQL</h3>
<p>A view is essentially an SQL results set that gets stored in the database under a label, so you can return to it later without having to rerun the query.</p>
<p>These are especially useful when you have a costly SQL query which you might need a number of times. So instead of running it over and over to generate the same results set, you can just do it once and save it as a view.</p>
<h4 id="heading-how-to-create-views-in-sql">How to Create Views in SQL</h4>
<p>To create a view, you can do so like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">VIEW</span> priority_users <span class="hljs-keyword">AS</span>
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span>
<span class="hljs-keyword">WHERE</span> country = ‘United Kingdom’;
</code></pre>
<p>Then in future, if you need to access the stored result set, you can do so like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> [priority_users];
</code></pre>
<h4 id="heading-how-to-replace-views-in-sql">How to Replace Views in SQL</h4>
<p>With the <code>CREATE OR REPLACE</code> command, you can update a view like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">OR</span> <span class="hljs-keyword">REPLACE</span> <span class="hljs-keyword">VIEW</span> [priority_users] <span class="hljs-keyword">AS</span>
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span>
<span class="hljs-keyword">WHERE</span> country = ‘United Kingdom’ <span class="hljs-keyword">OR</span> country=’USA’;
</code></pre>
<h4 id="heading-how-to-delete-views-in-sql">How to Delete Views in SQL</h4>
<p>To delete a view, simply use the <code>DROP VIEW</code> command.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">DROP</span> <span class="hljs-keyword">VIEW</span> priority_users;
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The majority of websites and applications use relational databases in some way or the other. This makes SQL extremely valuable to know as it allows you to create more complex, functional systems.</p>
<p>Happy learning!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React for Beginners: Complete React Cheatsheet for 2021 ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to the React for Beginners guide. It's designed to teach you all the core React concepts that you need to know to start building React applications in 2021. I created this resource to give you the most complete and beginner-friendly path to l... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-for-beginners-cheatsheet/</link>
                <guid isPermaLink="false">66d037bd871ae63f179f6bbc</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Fri, 14 May 2021 20:17:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/react-for-beginners-2021.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to the React for Beginners guide. It's designed to teach you all the core React concepts that you need to know to start building React applications in 2021.</p>
<p>I created this resource to give you the most complete and beginner-friendly path to learn React from the ground up.</p>
<p>By the end you will have a thorough understanding of tons of essential React concepts, including:</p>
<ul>
<li>The Why, What, and How of React</li>
<li>How to Easily Create React Apps</li>
<li>JSX and Basic Syntax</li>
<li>JSX Elements</li>
<li>Components and Props</li>
<li>Events in React</li>
<li>State and State Management</li>
<li>The Basics of React Hooks</li>
</ul>
<h3 id="heading-want-your-own-copy">Want Your Own Copy?‬ 📄</h3>
<p><strong><a target="_blank" href="https://reedbarger.com/resources/react-beginners-2021">Download the cheatsheet in PDF format here</a></strong> (it takes 5 seconds).</p>
<p>Here are some quick wins from grabbing the downloadable version:</p>
<ul>
<li>Quick reference guide to review however and whenever</li>
<li>Tons of copyable code snippets for easy reuse</li>
<li>Read this massive guide wherever suits you best. On the train, at your desk, standing in line... anywhere.</li>
</ul>
<p>There's a ton of great stuff to cover, so let's get started.</p>
<h2 id="heading-react-basics">React Basics</h2>
<h3 id="heading-what-is-react-really">What is React, really?</h3>
<p>React is officially defined as a "JavaScript library for creating user interfaces," but what does that really mean?</p>
<p>React is a library, made in JavaScript and which we code in JavaScript, to build great applications that run on the web.</p>
<h3 id="heading-what-do-i-need-to-know-to-learn-react">What do I need to know to learn React?</h3>
<p>In other words, you do need to have a basic understanding of JavaScript to become a solid React programmer?</p>
<p>The most basic JavaScript concepts you should be familiar with are variables, basic data types, conditionals, array methods, functions, and ES modules.</p>
<p>How do I learn all of these JavaScript skills? <a target="_blank" href="https://reactbootcamp.com/javascript-skills-for-react-2021/">Check out the comprehensive guide</a> to learn all of the JavaScript you need for React.</p>
<h3 id="heading-if-react-was-made-in-javascript-why-dont-we-just-use-javascript">If React was made in JavaScript, why don't we just use JavaScript?</h3>
<p>React was written in JavaScript, which was built from the ground up for the express purpose of building web applications and gives us tools to do so.</p>
<p>JavaScript is a 20+ year old language which was created for adding small bits of behavior to the browser through scripts and was not designed for creating complete applications.</p>
<p>In other words, while JavaScript was used to create React, they were created for very different purposes.</p>
<h3 id="heading-can-i-use-javascript-in-react-applications">Can I use JavaScript in React applications?</h3>
<p>Yes! You can include any valid JavaScript code within your React applications.</p>
<p>You can use any browser or window API, such as geolocation or the fetch API.</p>
<p>Also, since React (when it is compiled) runs in the browser, you can perform common JavaScript actions like DOM querying and manipulation.</p>
<h2 id="heading-how-to-create-react-apps">How to Create React Apps</h2>
<h3 id="heading-three-different-ways-to-create-a-react-application">Three different ways to create a React application</h3>
<ol>
<li>Putting React in an HTML file with external scripts </li>
<li>Using an in-browser React environment like CodeSandbox</li>
<li>Creating a React app on your computer using a tool like Create React App</li>
</ol>
<h3 id="heading-what-is-the-best-way-to-create-a-react-app">What is the best way to create a React app?</h3>
<p>Which is the best approach for you? The best way to create your application depends on what you want to do with it.</p>
<p>If you want to create a complete web application that you want to ultimately push to the web, it is best to create that React application on your computer using a tool like Create React App.</p>
<p>If you are interested in creating React apps on your computer, <a target="_blank" href="https://reactbootcamp.com/create-react-app-10-steps/">check out the complete guide to using Create React App</a>.</p>
<p>The easiest and most beginner-friendly way to create and build React apps for learning and prototyping is to use a tool like CodeSandbox. You can create a new React app in seconds by going to <a target="_blank" href="https://react.new">react.new</a>!</p>
<h2 id="heading-jsx-elements">JSX Elements</h2>
<h3 id="heading-jsx-is-a-powerful-tool-for-structuring-applications">JSX is a powerful tool for structuring applications</h3>
<p><strong>JSX</strong> is meant to make creating user interfaces with JavaScript applications easier.</p>
<p>It borrows its syntax from the most widely used programming language: HTML. As a result, JSX is a powerful tool to structure our applications.</p>
<p>The code example below is the most basic example of a React element which displays the text "Hello World":</p>
<pre><code class="lang-js">&lt;div&gt;Hello React!&lt;/div&gt;
</code></pre>
<p>Note that to be displayed in the browser, React elements need to be <strong>rendered</strong> (using <code>ReactDOM.render()</code>).</p>
<h3 id="heading-how-jsx-is-different-from-html">How JSX is different from HTML</h3>
<p>We can write valid HTML elements in JSX, but what differs slightly is the way some attributes are written.</p>
<p>Attributes that consist of multiple words are written in the camel-case syntax (like <code>className</code>) and have different names than standard HTML (<code>class</code>).</p>
<pre><code class="lang-js">&lt;div id=<span class="hljs-string">"header"</span>&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"title"</span>&gt;</span>Hello React!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<p>JSX has this different way of writing attributes because it is actually made using JavaScript functions (more on this later).</p>
<h3 id="heading-jsx-must-have-a-trailing-slash-if-it-is-made-of-one-tag">JSX must have a trailing slash if it is made of one tag</h3>
<p>Unlike standard HTML, elements like <code>input</code>, <code>img</code>, or <code>br</code> must close with a trailing forward slash for it to be valid JSX.</p>
<pre><code class="lang-js">&lt;input type=<span class="hljs-string">"email"</span> /&gt; <span class="hljs-comment">// &lt;input type="email"&gt; is a syntax error</span>
</code></pre>
<h3 id="heading-jsx-elements-with-two-tags-must-have-a-closing-tag">JSX elements with two tags must have a closing tag</h3>
<p>Elements that should have two tags, such as <code>div</code>, <code>main</code> or <code>button</code>, must have their closing, second tag in JSX, otherwise it will result in a syntax error.</p>
<pre><code class="lang-js">&lt;button&gt;Click me&lt;<span class="hljs-regexp">/button&gt; /</span><span class="hljs-regexp">/ &lt;button&gt; or &lt;/</span>button&gt; is a syntax error
</code></pre>
<h3 id="heading-how-jsx-elements-are-styled">How JSX elements are styled</h3>
<p>Inline styles are written differently as well as compared to plain HTML.</p>
<ul>
<li>Inline styles must not be included as a string, but within an object.</li>
<li>Once again, the style properties that we use must be written in the camel-case style.</li>
</ul>
<pre><code class="lang-js">&lt;h1 style={{ <span class="hljs-attr">color</span>: <span class="hljs-string">"blue"</span>, <span class="hljs-attr">fontSize</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">padding</span>: <span class="hljs-string">"0.5em 1em"</span> }}&gt;
  Hello React!
&lt;/h1&gt;;
</code></pre>
<p>Style properties that accept pixel values (like width, height, padding, margin, etc), can use integers instead of strings. For example, <code>fontSize: 22</code> instead of <code>fontSize: "22px"</code>.</p>
<h3 id="heading-jsx-can-be-conditionally-displayed">JSX can be conditionally displayed</h3>
<p>New React developers may be wondering how it is beneficial that React can use JavaScript code.</p>
<p>One simple example if that to conditionally hide or display JSX content, we can use any valid JavaScript conditional, like an if statement or switch statement.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isAuthUser = <span class="hljs-literal">true</span>;

<span class="hljs-keyword">if</span> (isAuthUser) {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Hello user!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>   
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
}
</code></pre>
<p>Where are we returning this code? Within a React component, which we will cover in a later section.</p>
<h3 id="heading-jsx-cannot-be-understood-by-the-browser">JSX cannot be understood by the browser</h3>
<p>As mentioned above, JSX is not HTML, but is composed of JavaScript functions.</p>
<p>In fact, writing <code>&lt;div&gt;Hello React&lt;/div&gt;</code> in JSX is just a more convenient and understandable way of writing code like the following:</p>
<pre><code class="lang-js">React.createElement(<span class="hljs-string">"div"</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">"Hello React!"</span>)
</code></pre>
<p>Both pieces of code will have the same output of "Hello React".</p>
<p>To write JSX and have the browser understand this different syntax, we must use a <strong>transpiler</strong> to convert JSX to these function calls.</p>
<p>The most common transpiler is called <strong>Babel.</strong></p>
<h2 id="heading-react-components">React Components</h2>
<h3 id="heading-what-are-react-components">What are React components?</h3>
<p>Instead of just rendering one or another set of JSX elements, we can include them within React <strong>components</strong>.</p>
<p>Components are created using what looks like a normal JavaScript function, but it's different in that it returns JSX elements.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Hello React!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;   
}
</code></pre>
<h3 id="heading-why-use-react-components">Why use React components?</h3>
<p>React components allow us to create more complex logic and structures within our React application than we would with JSX elements alone.</p>
<p>Think of React components as our custom React elements that have their own functionality.</p>
<p>As we know, functions allow us to create our own functionality and reuse it where we like across our application.</p>
<p>Components are reusable wherever we like across our app and as many times as we like.</p>
<h3 id="heading-components-are-not-normal-javascript-functions">Components are not normal JavaScript functions</h3>
<p>How would we render or display the returned JSX from the component above?</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Hello React!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;   
}

ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Greeting</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root));</span>
</code></pre>
<p>We use the <code>React</code> import to parse the JSX and <code>ReactDOM</code> to render our component to a <strong>root element</strong> with the id of "root."</p>
<h3 id="heading-what-can-react-components-return">What can React components return?</h3>
<p>Components can return valid JSX elements, as well as strings, numbers, booleans, the value <code>null</code>, as well as arrays and fragments.</p>
<p>Why would we want to return <code>null</code>? It is common to return <code>null</code> if we want a component to display nothing.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (isAuthUser) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello again!"</span>;   
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }
}
</code></pre>
<p>Another rule is that JSX elements must be wrapped in one parent element. Multiple sibling elements cannot be returned.</p>
<p>If you need to return multiple elements, but don't need to add another element to the DOM (usually for a conditional), you can use a special React component called a fragment.</p>
<p>Fragments can be written as <code>&lt;&gt;&lt;/&gt;</code> or when you import React into your file, with <code>&lt;React.Fragment&gt;&lt;/React.Fragment&gt;</code>.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> isAuthUser = <span class="hljs-literal">true</span>;  

  <span class="hljs-keyword">if</span> (isAuthUser) {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello again!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/&gt;</span></span>
    );
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }
}
</code></pre>
<p>Note that when attempting to return a number of JSX elements that are spread over multiple lines, we can return it all using a set of parentheses () as you see in the example above.</p>
<h3 id="heading-components-can-return-other-components">Components can return other components</h3>
<p>The most important thing components can return is other components.</p>
<p>Below is a basic example of a React application contained with in a component called <code>App</code> that returns multiple components:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;

<span class="hljs-keyword">import</span> Layout <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Layout'</span>;
<span class="hljs-keyword">import</span> Navbar <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Navbar'</span>;
<span class="hljs-keyword">import</span> Aside <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Aside'</span>;
<span class="hljs-keyword">import</span> Main <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Main'</span>;
<span class="hljs-keyword">import</span> Footer <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Footer'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Layout</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Navbar</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Main</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Aside</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Footer</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Layout</span>&gt;</span></span>
  );
}

ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>));
</code></pre>
<p>This is powerful because we are using the customization of components to describe what they are (that is, the Layout) and their function in our application. This tells us how they should be used just by looking at their name.</p>
<p>Additionally, we are using the power of JSX to compose these components. In other words, to use the HTML-like syntax of JSX to structure them in an immediately understandable way (like the Navbar is at the top of the app, the Footer at the bottom, and so on).</p>
<h3 id="heading-javascript-can-be-used-in-jsx-using-curly-braces">JavaScript can be used in JSX using curly braces</h3>
<p>Just as we can use JavaScript variables within our components, we can use them directly within our JSX as well.</p>
<p>There are a few core rules to using dynamic values within JSX, though:</p>
<ul>
<li>JSX can accept any primitive values (strings, booleans, numbers), but it will not accept plain objects.</li>
<li>JSX can also include expressions that resolve to these values.</li>
</ul>
<p>For example, conditionals can be included within JSX using the ternary operator, since it resolves to a value.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> isAuthUser = <span class="hljs-literal">true</span>;  

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{isAuthUser ? "Hello!" : null}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<h2 id="heading-props-in-react">Props in React</h2>
<h3 id="heading-components-can-be-passed-values-using-props">Components can be passed values using props</h3>
<p>Data passed to components in JavaScript are called <strong>props</strong>.</p>
<p>Props look identical to attributes on plain JSX/HTML elements, but you can access their values within the component itself.</p>
<p>Props are available in parameters of the component to which they are passed. Props are always included as properties of an object.</p>
<pre><code class="lang-js">ReactDOM.render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Greeting</span> <span class="hljs-attr">username</span>=<span class="hljs-string">"John!"</span> /&gt;</span></span>,
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>)
);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {props.username}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<h3 id="heading-props-cannot-be-directly-changed">Props cannot be directly changed</h3>
<p>Props must never be directly changed within the child component.</p>
<p>Another way to say this is that props should never be <strong>mutated</strong>, since props are a plain JavaScript object</p>
<pre><code class="lang-js"><span class="hljs-comment">// We cannot modify the props object:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">props</span>) </span>{
  props.username = <span class="hljs-string">"Doug"</span>;

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {props.username}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p>Components are considered pure functions. That is, for every input, we should be able to expect the same output. This means we cannot mutate the props object, only read from it.</p>
<h3 id="heading-special-props-the-children-prop">Special props: the children prop</h3>
<p>The <strong>children</strong> prop is useful if we want to pass elements / components as props to other components</p>
<p>The children prop is especially useful for when you want the same component (such as a Layout component) to wrap all other components.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Layout</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"container"</span>&gt;</span>{props.children}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">IndexPage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Layout</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Hero</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Footer</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Layout</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AboutPage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Layout</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">About</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Footer</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Layout</span>&gt;</span></span>
  );
}
</code></pre>
<p>The benefit of this pattern is that all styles applied to the Layout component will be shared with its child components.</p>
<h2 id="heading-lists-and-keys-in-react">Lists and Keys in React</h2>
<h3 id="heading-how-to-iterate-over-arrays-in-jsx-using-map">How to iterate over arrays in JSX using map</h3>
<p>How do we displays lists in JSX using array data? We use the <strong><code>.map()</code></strong> function to convert lists of data (arrays) into lists of elements.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> people = [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Fred"</span>];
<span class="hljs-keyword">const</span> peopleList = people.map(<span class="hljs-function">(<span class="hljs-params">person</span>) =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{person}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>);
</code></pre>
<p>You can use <code>.map()</code> for components as well as plain JSX elements.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> people = [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Fred"</span>];

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {people.map((person) =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">Person</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{person}</span> /&gt;</span>
      ))}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">{ name }</span>) </span>{
  <span class="hljs-comment">// we access the 'name' prop directly using object destructuring</span>
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This person's name is: {name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
}
</code></pre>
<h3 id="heading-the-importance-of-keys-in-lists">The importance of keys in lists</h3>
<p>Each React element within a list of elements needs a special <strong>key prop</strong>.</p>
<p>Keys are essential for React to be able to keep track of each element that is being iterated over with the <code>.map()</code> function.</p>
<p>React uses keys to performantly update individual elements when their data changes (instead of re-rendering the entire list).</p>
<p>Keys need to have unique values to be able to identify each of them according to their key value.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> people = [
    { <span class="hljs-attr">id</span>: <span class="hljs-string">"Ksy7py"</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-string">"6eAdl9"</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Bob"</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-string">"6eAdl9"</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Fred"</span> },
  ];

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {people.map((person) =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">Person</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{person.id}</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{person.name}</span> /&gt;</span>
      ))}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-state-and-managing-data-in-react">State and Managing Data in React</h2>
<h3 id="heading-what-is-state-in-react">What is state in React?</h3>
<p><strong>State</strong> is a concept that refers to how data in our application changes over time. </p>
<p>The significance of state in React is that it is a way to talk about our data separately from the user interface (what the user sees).</p>
<p>We talk about state management, because we need an effective way to keep track of and update data across our components as our user interacts with it.</p>
<p>To change our application from static HTML elements to a dynamic one that the user can interact with, we need state.</p>
<h3 id="heading-examples-of-how-to-use-state-in-react">Examples of how to use state in React</h3>
<p>We need to manage state often when our user wants to interact with our application. </p>
<p>When a user types into a form, we keep track of the form state in that component.</p>
<p>When we fetch data from an API to display to the user (such as posts in a blog), we need to save that data in state.</p>
<p>When we want to change data that a component is receiving from props, we use state to change it instead of mutating the props object.</p>
<h3 id="heading-introduction-to-react-hooks-with-usestate">Introduction to React hooks with useState</h3>
<p>The way to "create" state is React within a particular component is with the <code>useState</code> hook.</p>
<p>What is a hook? It is very much like a JavaScript function, but can only be used in a React function component at the top of the component.</p>
<p>We use hooks to "hook into" certain features, and <code>useState</code> gives us the ability to create and manage state.</p>
<p><code>useState</code> is an example of a core React hook that comes directly from the React library: <code>React.useState</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> state = React.useState(<span class="hljs-string">"Hello React"</span>);  

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{state[0]}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> <span class="hljs-comment">// displays "Hello React"</span>
}
</code></pre>
<p>How does <code>useState</code> work? Like a normal function, we can pass it a starting value (like "Hello React").</p>
<p>What is returned from useState is an array. To get access to the state variable and its value, we can use the first value in that array: <code>state[0]</code>.</p>
<p>There is a way to improve how we write this, however. We can use array destructuring to get direct access to this state variable and call it what we like, such as <code>title</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [title] = React.useState(<span class="hljs-string">"Hello React"</span>);  

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> <span class="hljs-comment">// displays "Hello React"</span>
}
</code></pre>
<p>What if we want to allow our user to update the greeting they see? If we include a form, a user can type in a new value. However, we need a way to update the initial value of our title.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [title] = React.useState(<span class="hljs-string">"Hello React"</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Update title"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>We can do so with the help of the second element in the array that useState returns. It is a setter function, to which we can pass whatever value we want the new state to be.</p>
<p>In our case, we want to get the value that is typed into the input when a user is in the process of typing. We can get it with the help of React events.</p>
<h3 id="heading-what-are-events-in-react">What are events in React?</h3>
<p>Events are ways to get data about a certain action that a user has performed in our app.</p>
<p>The most common props used to handle events are <code>onClick</code> (for click events), <code>onChange</code> (when a user types into an input), and <code>onSubmit</code> (when a form is submitted).</p>
<p>Event data is given to us by connecting a function to each of these props listed (there are many more to choose from than these three).</p>
<p>To get data about the event when our input is changed, we can add <code>onChange</code> on input and connect it to a function that will handle the event. This function will be called <code>handleInputChange</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [title] = React.useState(<span class="hljs-string">"Hello React"</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleInputChange</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"input changed!"</span>, event);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Update title"</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Note that in the code above, a new event will be logged to the browser's console whenever the user types into the input</p>
<p>Event data is provided to us as an object with many properties which are dependent upon the type of event.</p>
<h3 id="heading-how-to-update-state-in-react-with-usestate">How to update state in React with useState</h3>
<p>To update state with useState, we can use the second element that useState returns to us in its array.</p>
<p>This element is a function that will allow us to update the value of the state variable (the first element). Whatever we pass to this setter function when we call it will be put in state.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [title, setTitle] = React.useState(<span class="hljs-string">"Hello React"</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleInputChange</span>(<span class="hljs-params">event</span>) </span>{
    setTitle(event.target.value);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Update title"</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Using the code above, whatever the user types into the input (the text comes from <code>event.target.value</code>) will be put in state using <code>setTitle</code> and displayed within the <code>h1</code> element.</p>
<p>What is special about state and why it must be managed with a dedicated hook like useState is because a state update (such as when we call <code>setTitle</code>) causes a re-render.</p>
<p>A re-render is when a certain component renders or is displayed again based off the new data. If our components weren't re-rendered when data changed, we would never see the app's appearance change at all!</p>
<h2 id="heading-whats-next"><strong>What's Next</strong></h2>
<p>I hope you got a lot of out this guide.</p>
<p>If you want a copy of this cheatsheet to keep for learning purposes, you can <a target="_blank" href="https://reedbarger.com/resources/react-beginners-2021">download a complete PDF version of this cheatsheet here</a>.</p>
<p>Once you have finished with this guide, there are many things you can learn to advance your skills to the next level, including:</p>
<ul>
<li><a target="_blank" href="https://reactbootcamp.com/how-to-code-react-hooks/">How to write custom React hooks</a></li>
<li><a target="_blank" href="https://reactbootcamp.com/react-props-cheatsheet/">The complete guide to React props</a></li>
<li><a target="_blank" href="https://reactbootcamp.com/fetch-data-in-react/">How to fetch data in React from front to back</a></li>
<li><a target="_blank" href="https://reactbootcamp.com/react-app-node-backend/">How to build fullstack apps in React with Node</a></li>
<li><a target="_blank" href="https://reactbootcamp.com/what-to-know-about-react-state/">Learn more about React state</a></li>
<li><a target="_blank" href="https://reactbootcamp.com/react-router-cheatsheet/">How to add routing to your React app with React Router</a></li>
<li><a target="_blank" href="https://reactbootcamp.com/react-cheatsheet-2021/">Learn every part of React with the advanced React cheatsheet</a></li>
</ul>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Cheatsheet – 9 Common HTML Rendering Cases You Should Know ]]>
                </title>
                <description>
                    <![CDATA[ By Ondrej Polesny Whenever I'm starting with a new framework or it's been a while since I've used it, I always end up searching for the same simple things.  I'll Google how to render raw HTML, how to display a component based on a condition, how to a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-cheatsheet-html-rendering/</link>
                <guid isPermaLink="false">66d4609f3a8352b6c5a2aae3</guid>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 23 Apr 2021 21:40:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/04/teaser.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ondrej Polesny</p>
<p>Whenever I'm starting with a new framework or it's been a while since I've used it, I always end up searching for the same simple things. </p>
<p>I'll Google how to render raw HTML, how to display a component based on a condition, how to assign a class to an element, and so on.</p>
<p>That's why I created this cheat sheet with the nine most common tasks you will perform on a regular basis with React <a target="_blank" href="https://reactjs.org/docs/introducing-jsx.html">and JSX</a>. </p>
<p>I ordered them in the way I typically stumble upon them when building an application. In the examples below, the first code snippet will show the syntax, and the second one will show how to use it with real data.</p>
<h2 id="heading-how-to-output-data-into-html">How to Output Data into HTML</h2>
<p>The simplest use-case of all – render the value of a variable into HTML markup. It's usually the first test that shows you the app has processed the data and can render them:</p>
<pre><code class="lang-js">{ variable }
</code></pre>
<pre><code class="lang-js">{ metadata.subtitle.value }
</code></pre>
<h2 id="heading-how-to-add-a-standard-class-attribute">How to Add a Standard Class Attribute</h2>
<p>While many frameworks keep the HTML markup untouched, React does not allow the reserved word "class" to be used for styling. We need to use <code>className</code> instead, like this:</p>
<pre><code class="lang-js">&lt;... className=<span class="hljs-string">"classname"</span>&gt;
</code></pre>
<pre><code class="lang-js">&lt;div className=<span class="hljs-string">"sidebar__inner"</span>&gt;
</code></pre>
<h2 id="heading-how-to-output-data-into-html-attributes">How to Output Data into HTML Attributes</h2>
<p>This use-case is related to building links. But in many cases, you also need to fill attributes like title, data-{something-your-app-needs}, or even simple alt tags of images:</p>
<pre><code class="lang-js">&lt; ... name={variable}&gt;
</code></pre>
<pre><code class="lang-js">&lt;a href={<span class="hljs-string">`https://twitter.com/<span class="hljs-subst">${author.twitter.value}</span>`</span>}&gt;
</code></pre>
<h2 id="heading-how-to-output-raw-html">How to Output Raw HTML</h2>
<p>Some content is structured in another system, for example, rich text composed in a headless CMS. </p>
<p>In those cases, you typically use a tool like an SDK to build the HTML for you. This is how you can add it to your markup:</p>
<pre><code class="lang-js">&lt; ... dangerouslySetInnerHTML={{<span class="hljs-attr">__html</span>: variable}}&gt;&lt;/...&gt;
</code></pre>
<pre><code class="lang-js">&lt;div dangerouslySetInnerHTML={{<span class="hljs-attr">__html</span>: article.teaser}}&gt;&lt;/div&gt;
</code></pre>
<h2 id="heading-how-to-iterate-over-data-sets">How to Iterate Over Data Sets</h2>
<p>On index pages, sitemaps, search pages, or wherever you need to display data from a collection, React and JSX allow you to combine the (almost) almighty <code>map</code> function with HTML markup:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> components = collectionVariable.map(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Component</span> <span class="hljs-attr">data</span>=<span class="hljs-string">{item}</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.uniqueKey}</span> /&gt;</span></span>);
...
&lt;div&gt;{components}&lt;/div&gt;
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> articleComponents = articles.map(<span class="hljs-function">(<span class="hljs-params">article</span>) =&gt;</span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Article</span> <span class="hljs-attr">data</span>=<span class="hljs-string">{article}</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{article.id}</span> <span class="hljs-attr">...</span> /&gt;</span></span>);
...
&lt;div&gt;{articleComponents}&lt;/div&gt;
</code></pre>
<h2 id="heading-how-to-iterate-over-data-sets-with-an-index">How to Iterate Over Data Sets with an index</h2>
<p>This is the same use case, but it gives you access to an index of each iterated item. In some cases, the index can also be used to replace unique key:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> components = collectionVariable.map(<span class="hljs-function">(<span class="hljs-params">item, index</span>) =&gt;</span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Component</span> <span class="hljs-attr">data</span>=<span class="hljs-string">{item}</span> <span class="hljs-attr">index</span>=<span class="hljs-string">{index}</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{uniqueKey}</span> /&gt;</span></span>);
...
&lt;div&gt;{components}&lt;/div&gt;
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> articleComponents = articles.map(<span class="hljs-function">(<span class="hljs-params">article</span>) =&gt;</span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Article</span> <span class="hljs-attr">data</span>=<span class="hljs-string">{article}</span> <span class="hljs-attr">index</span>=<span class="hljs-string">{index}</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{article.id}</span> <span class="hljs-attr">...</span> /&gt;</span></span>);
...
&lt;div&gt;{articleComponents}&lt;/div&gt;
</code></pre>
<h2 id="heading-how-to-render-conditional-markup">How to Render Conditional Markup</h2>
<p>This is the typical <em>if</em> condition in JSX. It's often used during data loading to display pre-loaders or to just decide which portion of the markup to use based on data:</p>
<pre><code class="lang-js">{variable !== <span class="hljs-literal">null</span> &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">...</span> &gt;</span>}</span>
</code></pre>
<pre><code class="lang-js">{data.length &gt; <span class="hljs-number">0</span> &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> ... <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>}
</code></pre>
<h2 id="heading-how-to-render-conditional-markup-including-else-branch">How to Render Conditional Markup Including else branch</h2>
<p>The else branch is achieved by reversing the condition:</p>
<pre><code class="lang-js">{variable !== <span class="hljs-literal">null</span> &amp;&amp; &lt;... &gt;}
{variable == null &amp;&amp; &lt;... &gt;}
</code></pre>
<pre><code class="lang-js">{data.length &gt; <span class="hljs-number">0</span> &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> ... <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>}
{data.length == <span class="hljs-number">0</span> &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>}
</code></pre>
<h2 id="heading-how-to-pass-data-to-child-components">How to Pass Data to Child Components</h2>
<p>And finally, when you start using components, this is how you provide the children with data through props:</p>
<pre><code class="lang-js">&lt;component componentVariable={variable}&gt;
</code></pre>
<pre><code class="lang-js">&lt;links author={author}&gt;
</code></pre>
<p>I hope this saves you some Googling :-)</p>
<p>If you're looking for a printable (PDF) version, it's available on my <a target="_blank" href="https://ondrabus.com/react-vue-angular-cheatsheet">personal site</a> where you'll also find similar cheatsheets for Vue and Angular.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Props Cheatsheet: 10 Patterns You Should Know ]]>
                </title>
                <description>
                    <![CDATA[ Props are a powerful tool to use in React, but how do you use them effectively to write robust, reliable React components and applications? In this tutorial, we will be reviewing ten patterns you should use when working with props in React. We will n... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-props-cheatsheet/</link>
                <guid isPermaLink="false">66d037dfc1024fe75b758f50</guid>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Fri, 19 Feb 2021 17:02:51 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/02/react-props-cheatsheet-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Props are a powerful tool to use in React, but how do you use them effectively to write robust, reliable React components and applications?</p>
<p>In this tutorial, we will be reviewing ten patterns you should use when working with props in React.</p>
<p>We will not only touch on what these patterns are and how to use them, but you'll see how to use them on your own through practical, real-world examples.</p>
<p>Let’s get started!</p>
<h3 id="heading-want-your-own-copy">Want Your Own Copy?‬ 📄</h3>
<p><strong><a target="_blank" href="https://reedbarger.com/resources/react-props-2021">Click here to download the cheatsheet in PDF format</a></strong> (it takes 5 seconds).</p>
<p>It includes all of the essential information here as a convenient PDF guide.</p>
<h2 id="heading-1-react-props-can-be-passed-conditionally">1. React props can be passed conditionally</h2>
<p>Props that are passed to components can be thought of like arguments that are passed to a function. </p>
<p>If prop values are not passed a certain component, an error will not be thrown. Instead, within the component that prop will have a value of <code>undefined</code>. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-1-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you would like to be alerted to when a value is not passed as a prop to a component, you can use a tool like prop-types or TypeScript using these tools. </p>
<blockquote>
<p>With prop-types or TypeScript, we can tell React the props we are passing for a given component, what their values should be, and whether they are optional. </p>
</blockquote>
<p>In plain React, be aware that passing props can be something you forget to do. Also you might not pass a certain prop to a component, if you so choose. </p>
<h2 id="heading-2-react-props-passed-with-just-their-name-have-a-value-of-true">2. React props passed with just their name have a value of true</h2>
<p>Every prop must be given an associated value that is provided after the equals operator. </p>
<p>But what happens when we don't provide that equals operator as well as a value? </p>
<p>If you just provide the proper name on a component with nothing else, you pass a boolean value of true for that prop to the component. There is no need to write that a prop is equal to true. </p>
<p>Instead, you can just include the prop value, and it will be given the boolean value true when you use it in a component to which you pass it. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-2-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-3-react-props-can-be-accessed-as-an-object-or-destructured">3. React props can be accessed as an object or destructured</h2>
<p>There are a couple of patterns we can use for accessing prop values in our components. </p>
<p>Props can be accessed as an entire object which is usually called "props". Or they can be destructured, since props will always be an object, into separate variables. </p>
<p>If you have a lot of props that you're passing down to your component, it may be best to include them on the entire props object and access them by saying <code>props.propName</code>. </p>
<p>However, if you only have a few props that you're passing down to your component, you can immediately destructure them within the parameters of your function component. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-3-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can use ES6 object destructuring to include a set of curly braces within your function component's parameters, and immediately grab the properties off of the object, as well as declare them as separate variables. </p>
<p>This cuts down on our code and eliminates the need to say <code>props.propName</code> to get each props value.</p>
<h2 id="heading-4-react-components-can-be-passed-as-props-including-children">4. React components can be passed as props (including children)</h2>
<p>We've seen that props are very flexible, and if we don't pass them to a component, an error will not be thrown.</p>
<p>This flexibility is also extended to what we can pass as a prop. Not only can JSX elements be passed as props to components, but we can also pass other components as props. </p>
<p>In fact, there is a special type of prop that is automatically provided on the props object called <code>children</code>. </p>
<blockquote>
<p>We receive any children for a given component if any components or elements are passed between the opening and closing tags of that component. </p>
</blockquote>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-4-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The children prop allows us to compose our components in powerful ways. </p>
<p>This is especially helpful when we need to wrap one component around another, such as for styling, or to pass more component data to the children components to give two examples:</p>
<ol>
<li>Children props are very helpful when you want to make a generic layout component and give the same layout to all of the components that are passed as children. </li>
<li>Also, children are useful when you want to place a context provider from React context around your component tree to easily provide what is placed on context provider to all of its child components so they can receive the same data. </li>
</ol>
<h2 id="heading-5-anything-can-be-passed-as-a-prop-in-react-especially-functions">5. Anything can be passed as a prop in React (especially functions)</h2>
<p>Any normal JavaScript value can be passed as props as well, including functions. </p>
<p>There are some powerful patterns which have emerged, due to the ability to pass functions as props. A very common pattern is passing a function down to a child component as a prop, which can update the parent component's state, and then calling it within that child component. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-5-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Using this function that is passed down to update the parent's state and perform a function is called "lifting state up". </p>
</blockquote>
<p>Additionally, there are other patterns, such as the render props pattern, which also involve passing a function down to a child component to then be called back and perform some cross-component function. </p>
<h2 id="heading-6-update-a-react-props-value-with-state">6. Update a React prop's value with state</h2>
<p>Props cannot be directly updated. </p>
<p>To pass a prop value to a component, we cannot within that function component attempt to immediately change that prop's value. </p>
<blockquote>
<p>Prop values must be pure values. In other words, they cannot be mutated or changed directly. </p>
</blockquote>
<p>We know that in React if we want to change values over time, the appropriate means to do so is with state. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-6-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If we would like to pass in a prop value to a component and change it later on, we can give it to a stateful React hook to store that value as a variable. Then we can update it later on using the appropriate setter function. We can do so with the <code>useState</code> hook or the <code>useReducer</code> hook, for example. </p>
<h2 id="heading-7-react-props-can-be-spread-in-individually">7. React props can be spread in individually</h2>
<p>What if we have an object whose properties we want to pass down as individual prop values? </p>
<p>This object has a lot of properties, however. Do we need to manually create individual props and set the prop to <code>object.propertyName</code>?</p>
<p>No – instead of doing that for every property, we can very easily take the object and spread its properties down to a component as individual prop values using the object spread operator <code>{...myPropObject}</code>. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-7-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>By using this syntax, which is a feature in ES7, it enables us to automatically create individual props according to an object's property names, without having to write all those property names out. </p>
<p>It's very convenient when working with large objects with a lot of properties we want to pass as individual props to a component. </p>
<h2 id="heading-8-react-props-can-be-given-a-default-value-if-none-is-provided">8. React props can be given a default value if none is provided</h2>
<p>What if we already know that we are passing down a prop to one instance of a component, but we're not passing that prop to another instance of it? </p>
<p>Or maybe I know that the prop might not have a value. What do we do to give it a default value instead of just the value <code>undefined</code> if no prop value is passed to it? </p>
<p>If we are using destructuring to access that prop within our function component, we can use the equals operator to give it a default value. So if no prop value is passed for that prop, we can use the equals operator next to it and set it to a better default value. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-8-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Setting a default value is very important because the normal default value for a prop is <code>undefined</code>. This can help us avoid errors that may result from our expected prop value not being there.</p>
<h2 id="heading-9-react-props-can-be-renamed-to-avoid-errors">9. React props can be renamed to avoid errors</h2>
<p>Additionally, what if there is a naming conflict with one of our props? </p>
<p>What if we use a prop name across many of our components already and we see that there is another value within our component that has the same variable name? </p>
<p>Instead of having to go around and rename all of our prop values on all of our instances of our components, we can just use a colon after that prop name, if we're destructuring it, to give it an alias. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-9-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In other words, we give it a different name just in that instance. This will avoid the naming conflict as well as the error. </p>
<h2 id="heading-10-dont-attempt-to-destructure-react-props-multiple-times">10. Don't attempt to destructure React props multiple times</h2>
<p>If we are destructuring an object from our props object, be aware that it is possible to destructure that prop even further into its constituent properties. </p>
<p>However, it is not generally recommended to do so unless you are very confident that that object will always have those properties. </p>
<p>If one of those properties is missing and you attempt to destructure it multiple levels deep, it can give you a pretty nasty error when you're trying to access a property that doesn't exist. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/props-10-min.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Note that you can use destructuring as much as you'd like, but it can be hard to read up to a certain point and it also can be unreliable. If you're trying to access a property on an object, which may not exist, it will cause an error.</p>
<h2 id="heading-want-to-keep-this-guide-for-future-reference">Want to keep this guide for future reference?‬</h2>
<p><strong><a target="_blank" href="https://reedbarger.com/resources/react-props-2021">Click here to download the cheatsheet as a helpful PDF</a>.</strong></p>
<p>Here are 3 quick wins you get when you grab the downloadable version:</p>
<ul>
<li>You'll get tons of copyable code snippets for easy reuse in your own projects.</li>
<li>It is a great reference guide to strengthen your skills as a React developer and for job interviews.</li>
<li>You can take, use, print, read, and re-read this guide literally anywhere that you like.</li>
</ul>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Fetch API Cheatsheet: Nine of the Most Common API Requests ]]>
                </title>
                <description>
                    <![CDATA[ By Ondrej Polesny Almost every project needs to communicate with the outside world. If youʼre working with JavaScript frameworks, you'll most likely use Fetch API to do that.  But when you're working with the API, do you remember the syntax by heart ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/fetch-api-cheatsheet/</link>
                <guid isPermaLink="false">66d4608ab6b7f664236cbe27</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 16 Nov 2020 15:00:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/cover-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ondrej Polesny</p>
<p>Almost every project needs to communicate with the outside world. If youʼre working with JavaScript frameworks, you'll most likely use Fetch API to do that. </p>
<p>But when you're working with the API, do you remember the syntax by heart or do you need a little help?</p>
<p>I have written many articles about JavaScript and related things only to find myself later frequently (re)visiting them to refresh my memory or get some sample code that I know “is there somewhere.” </p>
<p>In this article, I aim to create another resource like that. I will list the 9 most common Fetch API requests. </p>
<p>Iʼm sure youʼve used them all many times. But wouldnʼt it be nice to avoid going through old projects to find the syntax of that specific request you used half a year ago? :)</p>
<h2 id="heading-why-use-the-fetch-api">Why Use the Fetch API?</h2>
<p>Nowadays, we are spoiled by all the services providing nice SDKs that abstract away the actual API requests. We just ask for data using typical language constructs and donʼt care about the actual data exchange. </p>
<p>But what if thereʼs no SDK for your chosen platform? Or what if youʼre building both the server and the client? In these cases, you need to handle the requests on your own. This is how you can do it using the Fetch API.</p>
<h3 id="heading-simple-get-request-with-the-fetch-api">Simple GET request with the Fetch API</h3>
<pre><code class="lang-js">fetch(<span class="hljs-string">'{url}'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response));
</code></pre>
<h3 id="heading-simple-post-request-with-the-fetch-api">Simple POST request with the Fetch API</h3>
<pre><code class="lang-js">fetch(<span class="hljs-string">'{url}'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'post'</span>
})
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response));
</code></pre>
<h3 id="heading-get-with-an-authorization-token-bearer-in-the-fetch-api">GET with an authorization token (Bearer) in the Fetch API</h3>
<pre><code class="lang-js">fetch(<span class="hljs-string">'{url}'</span>, {
    <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Authorization'</span>: <span class="hljs-string">'Basic {token}'</span>
    }
})
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response));
</code></pre>
<h3 id="heading-get-with-querystring-data-in-the-fetch-api">GET with querystring data in the Fetch API</h3>
<pre><code class="lang-js">fetch(<span class="hljs-string">'{url}?var1=value1&amp;var2=value2'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response));
</code></pre>
<h3 id="heading-get-with-cors-in-the-fetch-api">GET with CORS in the Fetch API</h3>
<pre><code class="lang-js">fetch(<span class="hljs-string">'{url}'</span>, {
    <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>
})
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response));
</code></pre>
<h3 id="heading-post-with-authorization-token-and-querystring-data-in-the-fetch-api">POST with authorization token and querystring data in the Fetch API</h3>
<pre><code class="lang-js">fetch(<span class="hljs-string">'{url}?var1=value1&amp;var2=value2'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'post'</span>,
    <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Authorization'</span>: <span class="hljs-string">'Bearer {token}'</span>
    }
})
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response));
</code></pre>
<h3 id="heading-post-with-form-data-in-the-fetch-api">POST with form data in the Fetch API</h3>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> formData = <span class="hljs-keyword">new</span> FormData();
formData.append(<span class="hljs-string">'field1'</span>, <span class="hljs-string">'value1'</span>);
formData.append(<span class="hljs-string">'field2'</span>, <span class="hljs-string">'value2'</span>);

fetch(<span class="hljs-string">'{url}'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'post'</span>,
    <span class="hljs-attr">body</span>: formData
})
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response));
</code></pre>
<h3 id="heading-post-with-json-data-in-the-fetch-api">POST with JSON data in the Fetch API</h3>
<pre><code class="lang-js">fetch(<span class="hljs-string">'{url}'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'post'</span>,
    <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
    },
    <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
        <span class="hljs-string">'field1'</span>: <span class="hljs-string">'value1'</span>,
        <span class="hljs-string">'field2'</span>: <span class="hljs-string">'value2'</span>
    })
})
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response));
</code></pre>
<h3 id="heading-post-with-json-data-and-cors-in-the-fetch-api">POST with JSON data and CORS in the Fetch API</h3>
<pre><code class="lang-js">fetch(<span class="hljs-string">'{url}'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'post'</span>,
    <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
    <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
    },
    <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
        <span class="hljs-string">'field1'</span>: <span class="hljs-string">'value1'</span>,
        <span class="hljs-string">'field2'</span>: <span class="hljs-string">'value2'</span>
    })
})
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response));
</code></pre>
<h2 id="heading-how-to-process-the-results-of-the-fetch-api-request">How to process the results of the Fetch API request</h2>
<p>The Fetch API returns a <em>Promise</em>. Thatʼs why Iʼm always using <code>.then()</code> and a callback function for processing the response:</p>
<pre><code class="lang-js">fetch(...).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
    <span class="hljs-comment">// process the response</span>
}
</code></pre>
<p>But you can also await the result if youʼre in an async function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">let</span> data = <span class="hljs-keyword">await</span> fetch(...);
    <span class="hljs-comment">// process the response</span>
}
</code></pre>
<p>Now letʼs take a look at how we can extract the data from the response:</p>
<h3 id="heading-how-to-check-the-status-code-of-the-fetch-api-response">How to check the status code of the Fetch API response</h3>
<p>When sending POST, PATCH, and PUT requests, we are typically interested in the return status code:</p>
<pre><code class="lang-js">fetch(...)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
        <span class="hljs-keyword">if</span> (response.status == <span class="hljs-number">200</span>){
            <span class="hljs-comment">// all OK</span>
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">console</span>.log(response.statusText);
        }
    });
</code></pre>
<h3 id="heading-how-to-get-a-simple-value-of-the-fetch-api-response">How to get a simple value of the Fetch API response</h3>
<p>Some API endpoints may send back an identifier of a new database record that was created using your data:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> userId;

fetch(...)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.text())
    .then(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
        userId = id;
        <span class="hljs-built_in">console</span>.log(userId)
    });
</code></pre>
<h3 id="heading-how-to-convert-json-data-of-the-fetch-api-response">How to convert JSON data of the Fetch API response</h3>
<p>But in most cases, youʼll receive JSON data in the response body:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> dataObj;

fetch(...)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        dataObj = data;
        <span class="hljs-built_in">console</span>.log(dataObj)
    });
</code></pre>
<p>Keep in mind that you can access the data only after both Promises are resolved. This is sometimes a bit confusing, so I always prefer to use async methods and await the results:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">var</span> dataObj;

    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(...);
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    dataObj = data;
    <span class="hljs-built_in">console</span>.log(dataObj);
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>These samples should have you covered in most situations. </p>
<p>Is there something that I missed, a request you use on a daily basis? Or something else youʼre struggling with? Let me know on <a target="_blank" href="https://twitter.com/ondrabus">Twitter</a>, and Iʼll cover it in another article :-)</p>
<p>Oh, and you can get this cheatsheet in a <a target="_blank" href="https://ondrabus.com/fetch-api-cheatsheet">printable form too</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The JavaScript + Firestore Tutorial for 2020: Learn by Example ]]>
                </title>
                <description>
                    <![CDATA[ Cloud Firestore is a blazing-fast, serverless NoSQL database, perfect for powering web and mobile apps of any size. Grab the complete guide to learning Firestore, created to show you how to use Firestore as the engine for your own amazing projects fr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-firestore-tutorial-for-2020-learn-by-example/</link>
                <guid isPermaLink="false">66d037f1871ae63f179f6bc8</guid>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Firebase ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ NoSQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Thu, 16 Jul 2020 13:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/07/The-Firestore-Tutorial-2020.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Cloud Firestore is a blazing-fast, serverless NoSQL database, perfect for powering web and mobile apps of any size. <a target="_blank" href="https://reedbarger.com/resources/javascript-firestore-2020/">Grab the complete guide to learning Firestore</a>, created to show you how to use Firestore as the engine for your own amazing projects from front to back.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<p>Getting Started with Firestore</p>
<ul>
<li>What is Firestore? Why Should You Use It?</li>
<li>Setting Up Firestore in a JavaScript Project</li>
<li>Firestore Documents and Collections</li>
<li>Managing our Database with the Firebase Console</li>
</ul>
<p>Fetching Data with Firestore</p>
<ul>
<li>Getting Data from a Collection with .get()</li>
<li>Subscribing to a Collection with .onSnapshot()</li>
<li>Difference between .get() and .onSnapshot()</li>
<li>Unsubscribing from a collection</li>
<li>Getting individual documents</li>
</ul>
<p>Changing Data with Firestore</p>
<ul>
<li>Adding document to a collection with .add()</li>
<li>Adding a document to a collection with .set()</li>
<li>Updating existing data</li>
<li>Deleting data</li>
</ul>
<p>Essential Patterns</p>
<ul>
<li>Working with subcollections</li>
<li>Useful methods for Firestore fields</li>
<li>Querying with .where()</li>
<li>Ordering and limiting data</li>
</ul>
<p><a target="_blank" href="https://reedbarger.com/resources/javascript-firestore-2020/">Note: you can download a PDF version of this tutorial so you can read it offline.</a></p>
<h3 id="heading-what-is-firestore-why-should-you-use-it">What is Firestore? Why Should You Use It?</h3>
<p>Firestore is a very flexible, easy to use database for mobile, web and server development. If you're familiar with Firebase's realtime database, Firestore has many similarities, but with a different (arguably more declarative) API.</p>
<p>Here are some of the features that Firestore brings to the table:</p>
<h4 id="heading-easily-get-data-in-realtime">⚡️Easily get data in realtime</h4>
<p>Like the Firebase realtime database, Firestore provides useful methods such as .onSnapshot() which make it a breeze to listen for updates to your data in real time. It makes Firestore an ideal choice for projects that place a premium on displaying and using the most recent data (chat applications, for instance).</p>
<h4 id="heading-flexibility-as-a-nosql-database">Flexibility as a NoSQL Database</h4>
<p>Firestore is a very flexible option for a backend because it is a NoSQL database. NoSQL means that the data isn't stored in tables and columns as a standard SQL database would be. It is structured like a key-value store, as if it was one big JavaScript object. </p>
<p>In other words, there's no schema or need to describe what data  our database will store. As long as we provide valid keys and values, Firestore will store it. </p>
<h4 id="heading-effortlessly-scalable">↕️ Effortlessly scalable</h4>
<p>One great benefit of choosing Firestore for your database is the very powerful infrastructure that it builds upon that enables you to scale your application very easily. Both vertically and horizontally. No matter whether you have hundreds or millions of users. Google's servers will be able to handle whatever load you place upon it.</p>
<p>In short, Firestore is a great option for applications both small and large. For small applications it's powerful because we can do a lot without much setup and create projects very quickly with them. Firestore is well-suited for large projects due to it's scalability.</p>
<h3 id="heading-setting-up-firestore-in-a-javascript-project">Setting Up Firestore in a JavaScript Project</h3>
<blockquote>
<p>We're going to be using the Firestore SDK for JavaScript. Throughout this cheatsheet, we'll cover how to use Firestore within the context of a JavaScript project. In spite of this, the concepts we'll cover here are easily transferable to any of the available Firestore client libraries. </p>
</blockquote>
<p> To get started with Firestore, we'll head to the Firebase console. You can visit that by going to <a target="_blank" href="https://firebase.com">firebase.google.com</a>. You'll need to have a Google account to sign in. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/firebase.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once we're signed in, we'll create a new project and give it a name. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/create-a-project.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once our project is created, we'll select it. After that, on our project's dashboard, we'll select the code button. </p>
<p>This will give us the code we need to integrate Firestore with our JavaScript project. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/firebase-integration.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Usually if you're setting this up in any sort of JavaScript application, you'll want to put this in a dedicated file called firebase.js. If you're using any JavaScript library that has a package.json file, you'll want to install the Firebase dependency with npm or yarn.</p>
<pre><code class="lang-bash">// with npm
npm i firebase

// with yarn
yarn add firebase
</code></pre>
<p>Firestore can be used either on the client or server. If you are using Firestore with Node, you'll need to use the CommonJS syntax with require. Otherwise, if you're using JavaScript in the client, you'll import firebase using ES Modules.</p>
<pre><code class="lang-js"><span class="hljs-comment">// with Commonjs syntax (if using Node)</span>
<span class="hljs-keyword">const</span> firebase = <span class="hljs-built_in">require</span>(<span class="hljs-string">"firebase/app"</span>);
<span class="hljs-built_in">require</span>(<span class="hljs-string">"firebase/firestore"</span>);

<span class="hljs-comment">// with ES Modules (if using client-side JS, like React)</span>
<span class="hljs-keyword">import</span> firebase <span class="hljs-keyword">from</span> <span class="hljs-string">'firebase/app'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'firebase/firestore'</span>;

<span class="hljs-keyword">var</span> firebaseConfig = {
  <span class="hljs-attr">apiKey</span>: <span class="hljs-string">"AIzaSyDpLmM79mUqbMDBexFtOQOkSl0glxCW_ds"</span>,
  <span class="hljs-attr">authDomain</span>: <span class="hljs-string">"lfasdfkjkjlkjl.firebaseapp.com"</span>,
  <span class="hljs-attr">databaseURL</span>: <span class="hljs-string">"https://lfasdlkjkjlkjl.firebaseio.com"</span>,
  <span class="hljs-attr">projectId</span>: <span class="hljs-string">"lfasdlkjkjlkjl"</span>,
  <span class="hljs-attr">storageBucket</span>: <span class="hljs-string">"lfasdlkjkjlkjl.appspot.com"</span>,
  <span class="hljs-attr">messagingSenderId</span>: <span class="hljs-string">"616270824980"</span>,
  <span class="hljs-attr">appId</span>: <span class="hljs-string">"1:616270824990:web:40c8b177c6b9729cb5110f"</span>,
};
<span class="hljs-comment">// Initialize Firebase</span>
firebase.initializeApp(firebaseConfig);
</code></pre>
<h3 id="heading-firestore-collections-and-documents">Firestore Collections and Documents</h3>
<p>There are two key terms that are essential to understanding how to work with Firestore: <strong>documents</strong> and <strong>collections</strong>. </p>
<p>Documents are individual pieces of data in our database. You can think of documents to be much like simple JavaScript objects. They consist of key-value pairs, which we refer to as <strong>fields</strong>. The values of these fields can be strings, numbers, Booleans, objects, arrays, and even binary data.</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span> -&gt; { <span class="hljs-attr">key</span>: value }
</code></pre>
<p>Sets of these documents of these documents are known as collections. Collections are very much like arrays of objects. Within a collection, each document is linked to a given identifier (id). </p>
<pre><code class="lang-js">collection -&gt; [{ <span class="hljs-attr">id</span>: doc }, { <span class="hljs-attr">id</span>: doc }]
</code></pre>
<h3 id="heading-managing-our-database-with-the-firestore-console">Managing our database with the Firestore Console</h3>
<p>Before we can actually start working with our database we need to create it.</p>
<p>Within our Firebase console, go to the 'Database' tab and create your Firestore database. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/firestore.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you've done that, we will start in test mode and enable all reads and writes to our database. In other words, we will have open access to get and change data in our database. If we were to add Firebase authentication, we could restrict access only to authenticated users. </p>
<p>After that, we'll be taken to our database itself, where we can start creating collections and documents. The root of our database will be a series of collections, so let's make our first collection. </p>
<p>We can select 'Start collection' and give it an id. Every collection is going to have an id or a name. For our project, we're going to keep track of our users' favorite books. We'll give our first collection the id 'books'. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/collection-id.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Next, we'll add our first document with our newly-created 'books' collection. </p>
<p>Each document is going to have an id as well, linking it to the collection in which it exists. </p>
<p>In most cases we're going to use an  option to give it an automatically generated ID. So we can hit the button 'auto id' to do so, after which we need to provide a field, give it a type, as well as a value. </p>
<p>For our first book, we'll make a 'title' field of type 'string', with the value 'The Great Gatsby', and hit save. </p>
<p>After that, we should see our first item in our database.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/first-item.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-getting-data-from-a-collection-with-get">Getting data from a collection with .get()</h3>
<p>To get access Firestore use all of the methods it provides, we use <code>firebase.firestore()</code>. This method need to be executed every time we want to interact with our Firestore database. </p>
<p>I would recommend creating a dedicated variable to store a single reference to Firestore. Doing so helps to cut down on the amount of code you write across your app. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> db = firebase.firestore();
</code></pre>
<blockquote>
<p>In this cheatsheet, however, I'm going to stick to using the firestore method each time to be as clear as possible.</p>
</blockquote>
<p>To reference a collection, we use the <code>.collection()</code> method and provide a collection's id as an argument. To get a reference to the books collection we created, just pass in the string 'books'.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> booksRef = firebase.firestore().collection(<span class="hljs-string">'books'</span>);
</code></pre>
<p>To get all of the document data from a collection, we can chain on the <code>.get()</code> method. </p>
<p><code>.get()</code> returns a promise, which means we can resolve it either using a <code>.then()</code> callback or we can use the async-await syntax if we're executing our code within an async function. </p>
<p>Once our promises is resolved in one way or another, we get back what's known as a <strong>snapshot</strong>. </p>
<p>For a collection query that snapshot is going to consist of a number of individual documents. We can access them by saying <code>snapshot.docs</code>. </p>
<p>From each document, we can get the id as a separate property, and the rest of the data using the <code>.data()</code> method. </p>
<p>Here's what our entire query looks like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> booksRef = firebase
  .firestore()
  .collection(<span class="hljs-string">"books"</span>);

booksRef
  .get()
  .then(<span class="hljs-function">(<span class="hljs-params">snapshot</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> data = snapshot.docs.map(<span class="hljs-function">(<span class="hljs-params">doc</span>) =&gt;</span> ({
      <span class="hljs-attr">id</span>: doc.id,
      ...doc.data(),
    }));
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All data in 'books' collection"</span>, data); 
    <span class="hljs-comment">// [ { id: 'glMeZvPpTN1Ah31sKcnj', title: 'The Great Gatsby' } ]</span>
  });
</code></pre>
<h3 id="heading-subscribing-to-a-collection-with-onsnapshot">Subscribing to a collection with .onSnapshot()</h3>
<p>The <code>.get()</code> method simply returns all the data within our collection. </p>
<p>To leverage some of Firestore's realtime capabilities we can subscribe to a collection, which gives us the current value of the documents in that collection, whenever they are updated. </p>
<p>Instead of using the <code>.get()</code> method, which is for querying a single time, we use the <code>.onSnapshot()</code> method. </p>
<pre><code class="lang-js">firebase
  .firestore()
  .collection(<span class="hljs-string">"books"</span>)
  .onSnapshot(<span class="hljs-function">(<span class="hljs-params">snapshot</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> data = snapshot.docs.map(<span class="hljs-function">(<span class="hljs-params">doc</span>) =&gt;</span> ({
      <span class="hljs-attr">id</span>: doc.id,
      ...doc.data(),
    }));
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All data in 'books' collection"</span>, data);
  });
</code></pre>
<p>In the code above, we're using what's known as method chaining instead of creating a separate variable to reference the collection.</p>
<p>What's powerful about using firestore is that we can chain a bunch of methods one after another, making for more declarative, readable code.</p>
<p>Within onSnapshot's callback, we get direct access to the snapshot of our collection, both now and whenever it's updated in the future. Try manually updating our one document and you'll see that <code>.onSnapshot()</code> is listening for any changes in this collection.</p>
<h3 id="heading-difference-between-get-and-onsnapshot">Difference between .get() and .onSnapshot()</h3>
<p>The difference between the get and the snapshot methods is that get returns a promise, which needs to be resolved, and only then we get the snapshot data.</p>
<p><code>.onSnapshot</code>, however, utilizes synchronous callback function, which gives us direct access to the snapshot. </p>
<p>This is important to keep in mind when it comes to these different methods--we have to know which of them return a promise and which are synchronous. </p>
<h3 id="heading-unsubscribing-from-a-collection-with-unsubscribe">Unsubscribing from a collection with unsubscribe()</h3>
<p>Note additionally that <code>.onSnapshot()</code> returns a function which we can use to unsubscribe and stop listening on a given collection. </p>
<p>This is important in cases where the user, for example, goes away from a given page where we're displaying a collection's data. Here's an example, using the library React were we are calling unsubscribe within the useEffect hook. </p>
<p>When we do so this is going to make sure that when our component is unmounted (no longer displayed within the context of our app) that we're no longer listening on the collection data that we're using in this component.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [books, setBooks] = React.useState([]);

  React.useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> unsubscribe = firebase
      .firestore()
      .collection(<span class="hljs-string">"books"</span>)
      .onSnapshot(<span class="hljs-function">(<span class="hljs-params">snapshot</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> data = snapshot.docs.map(<span class="hljs-function">(<span class="hljs-params">doc</span>) =&gt;</span> ({
          <span class="hljs-attr">id</span>: doc.id,
          ...doc.data(),
        }));
        setBooks(data);
      });
  }, []);

  <span class="hljs-keyword">return</span> books.map(<span class="hljs-function"><span class="hljs-params">book</span> =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BookList</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{book.id}</span> <span class="hljs-attr">book</span>=<span class="hljs-string">{book}</span> /&gt;</span></span>)
}
</code></pre>
<h3 id="heading-getting-individual-documents-with-doc">Getting Individual Documents with .doc()</h3>
<p>When it comes to getting a document within a collection., the process is just the same as getting an entire collection: we need to first create a reference to that document, and then use the get method to grab it.</p>
<p>After that, however, we use the <code>.doc()</code> method chained on to the collection method. In order to create a reference, we need to grab this id from the database if it was auto generated. After that, we can chain on <code>.get()</code> and resolve the promise. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bookRef = firebase
  .firestore()
  .collection(<span class="hljs-string">"books"</span>)
  .doc(<span class="hljs-string">"glMeZvPpTN1Ah31sKcnj"</span>);

bookRef.get().then(<span class="hljs-function">(<span class="hljs-params">doc</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (!doc.exists) <span class="hljs-keyword">return</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Document data:"</span>, doc.data());
  <span class="hljs-comment">// Document data: { title: 'The Great Gatsby' }</span>
});
</code></pre>
<p>Notice the conditional <code>if (!doc.exists) return;</code> in the code above.</p>
<p>Once we get the document back, it's essential to check to see whether it exists. </p>
<p>If we don't, there'll be an error in getting our document data. The way to check and see if our document exists is by saying, if <code>doc.exists</code>, which returns a true or false value. </p>
<p>If this expression returns false, we want to return from the function or maybe throw an error. If <code>doc.exists</code> is true, we can get the data from <code>doc.data</code>.</p>
<h3 id="heading-adding-document-to-a-collection-with-add">Adding document to a collection with .add()</h3>
<p>Next, let's move on to changing data. The easiest way to add a new document to a collection is with the <code>.add()</code> method. </p>
<p>All you need to do is select a collection reference (with <code>.collection()</code>) and chain on <code>.add()</code>. </p>
<p>Going back to our definition of documents as being like JavaScript objects, we need to pass an object to the <code>.add()</code> method and specify all the fields we want to be on the document. </p>
<p>Let's say we want to add another book, 'Of Mice and Men':</p>
<pre><code class="lang-js">firebase
  .firestore()
  .collection(<span class="hljs-string">"books"</span>)
  .add({
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Of Mice and Men"</span>,
  })
  .then(<span class="hljs-function">(<span class="hljs-params">ref</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Added doc with ID: "</span>, ref.id);
    <span class="hljs-comment">// Added doc with ID:  ZzhIgLqELaoE3eSsOazu</span>
  });
</code></pre>
<p>The <code>.add</code> method returns a promise and from this resolved promise, we get back a reference to the created document, which gives us information such as the created id. </p>
<p>The <code>.add()</code> method auto generates an id for us. Note that we can't use this ref directly to get data. We can however pass the ref to the doc method to create another query.</p>
<h3 id="heading-adding-a-document-to-a-collection-with-set">Adding a document to a collection with .set()</h3>
<p>Another way to add a document to a collection is with the <code>.set()</code> method. </p>
<p>Where set differs from add lies in the need to specify our own id upon adding the data. </p>
<p>This requires chaining on the <code>.doc()</code> method with the id that you want to use. Also, note how when the promise is resolved from <code>.set()</code>, we don't get a reference to the created document:</p>
<pre><code class="lang-js">firebase
  .firestore()
  .collection(<span class="hljs-string">"books"</span>)
  .doc(<span class="hljs-string">"another book"</span>)
  .set({
    <span class="hljs-attr">title</span>: <span class="hljs-string">"War and Peace"</span>,
  })
  .then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Document created"</span>);
  });
</code></pre>
<p>Additionally, when we use <code>.set()</code> with an existing document, it will, by default, overwrite that document. </p>
<p>If we want to merge, an old document with a new document instead of overwriting it, we need to pass an additional argument to <code>.set()</code> and provide the property <code>merge</code> set to true.</p>
<pre><code class="lang-js"><span class="hljs-comment">// use .set() to merge data with existing document, not overwrite</span>

<span class="hljs-keyword">const</span> bookRef = firebase
  .firestore()
  .collection(<span class="hljs-string">"books"</span>)
  .doc(<span class="hljs-string">"another book"</span>);

bookRef
  .set({
    <span class="hljs-attr">author</span>: <span class="hljs-string">"Lev Nikolaevich Tolstoy"</span>
  }, { <span class="hljs-attr">merge</span>: <span class="hljs-literal">true</span> })
  .then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Document merged"</span>);

    bookRef
      .get()
      .then(<span class="hljs-function"><span class="hljs-params">doc</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Merged document: "</span>, doc.data());
      <span class="hljs-comment">// Merged document:  { title: 'War and Peace', author: 'Lev Nikolaevich Tolstoy' }</span>
    });
  });
</code></pre>
<h3 id="heading-updating-existing-data-with-update">Updating existing data with .update()</h3>
<p>When it comes to updating data we use the update method, like <code>.add()</code> and <code>.set()</code> it returns a promise.</p>
<p>What's helpful about using <code>.update()</code> is that, unlike <code>.set()</code>, it won't overwrite the entire document. Also like <code>.set()</code>, we need to reference an individual document. </p>
<p>When you use <code>.update()</code>, it's important to use some error handling, such as the <code>.catch()</code> callback in the event that the document doesn't exist. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bookRef = firebase.firestore().collection(<span class="hljs-string">"books"</span>).doc(<span class="hljs-string">"another book"</span>);

bookRef
  .update({
    <span class="hljs-attr">year</span>: <span class="hljs-number">1869</span>,
  })
  .then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Document updated"</span>); <span class="hljs-comment">// Document updated</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error updating doc"</span>, error);
  });
</code></pre>
<h3 id="heading-deleting-data-with-delete">Deleting data with .delete()</h3>
<p>We can delete a given document collection by referencing it by it's id and executing the <code>.delete()</code> method, simple as that. It also returns a promise.</p>
<p>Here is a basic example of deleting a book with the id "another book":</p>
<pre><code class="lang-js">firebase
  .firestore()
  .collection(<span class="hljs-string">"books"</span>)
  .doc(<span class="hljs-string">"another book"</span>)
  .delete()
  .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Document deleted"</span>)) <span class="hljs-comment">// Document deleted</span>
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error deleting document"</span>, error));
</code></pre>
<blockquote>
<p>Note that the official Firestore documentation does not recommend to delete entire collections, only individual documents.</p>
</blockquote>
<h3 id="heading-working-with-subcollections">Working with Subcollections</h3>
<p>Let's say that we made a misstep in creating our application, and instead of just adding books we also want to connect them to the users that made them. T</p>
<p>The way that we want to restructure the data is by making a collection called 'users' in the root of our database, and have 'books' be a subcollection of 'users'. This will allow users to have their own collections of books. How do we set that up? </p>
<p>References to the subcollection 'books' should look something like this: </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> userBooksRef = firebase
  .firestore()
  .collection(<span class="hljs-string">'users'</span>)
  .doc(<span class="hljs-string">'user-id'</span>)
  .collection(<span class="hljs-string">'books'</span>);
</code></pre>
<p>Note additionally that we can write this all within a single <code>.collection()</code> call using forward slashes. </p>
<p>The above code is equivalent to the follow, where the collection reference must have an odd number of segments. If not, Firestore will throw an error. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> userBooksRef = firebase
  .firestore()
  .collection(<span class="hljs-string">'users/user-id/books'</span>);
</code></pre>
<p>To create the subcollection itself, with one document (another Steinbeck novel, 'East of Eden') run the following. </p>
<pre><code class="lang-js">firebase.firestore().collection(<span class="hljs-string">"users/user-1/books"</span>).add({
  <span class="hljs-attr">title</span>: <span class="hljs-string">"East of Eden"</span>,
});
</code></pre>
<p>Then, getting that newly created subcollection would look like the following based off of the user's ID.</p>
<pre><code class="lang-js">firebase
  .firestore()
  .collection(<span class="hljs-string">"users/user-1/books"</span>)
  .get()
  .then(<span class="hljs-function">(<span class="hljs-params">snapshot</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> data = snapshot.docs.map(<span class="hljs-function">(<span class="hljs-params">doc</span>) =&gt;</span> ({
      <span class="hljs-attr">id</span>: doc.id,
      ...doc.data(),
    }));
    <span class="hljs-built_in">console</span>.log(data); 
    <span class="hljs-comment">// [ { id: 'UO07aqpw13xvlMAfAvTF', title: 'East of Eden' } ]</span>
  });
</code></pre>
<h3 id="heading-useful-methods-for-firestore-fields">Useful methods for Firestore fields</h3>
<p>There are some useful tools that we can grab from Firestore that enables us to work with our field values a little bit easier. </p>
<p>For example, we can generate a timestamp for whenever a given document is created or updated with the following helper from the <code>FieldValue</code> property. </p>
<p>We can of course create our own date values using JavaScript, but using a server timestamp lets us know exactly when data is changed or created from Firestore itself. </p>
<pre><code class="lang-js">firebase
  .firestore()
  .collection(<span class="hljs-string">"users"</span>)
  .doc(<span class="hljs-string">"user-2"</span>)
  .set({
    <span class="hljs-attr">created</span>: firebase.firestore.FieldValue.serverTimestamp(),
  })
  .then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Added user"</span>); <span class="hljs-comment">// Added user</span>
  });
</code></pre>
<p>Additionally, say we have a field on a document which keeps track of a certain number, say the number of books a user has created. Whenever a user creates a new book we want to increment that by one. </p>
<p>An easy way to do this, instead of having to first make a <code>.get()</code> request, is to use another field value helper called <code>.increment()</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> userRef = firebase.firestore().collection(<span class="hljs-string">"users"</span>).doc(<span class="hljs-string">"user-2"</span>);

userRef
  .set({
    <span class="hljs-attr">count</span>: firebase.firestore.FieldValue.increment(<span class="hljs-number">1</span>),
  })
  .then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Updated user"</span>);

    userRef.get().then(<span class="hljs-function">(<span class="hljs-params">doc</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Updated user data: "</span>, doc.data());
    });
  });
</code></pre>
<h3 id="heading-querying-with-where">Querying with .where()</h3>
<p>What if we want to get data from our collections based on certain conditions? For example, say we want to get all of the users that have submitted one or more books?</p>
<p>We can write such a query with the help of the <code>.where()</code> method. First we reference a collection and then chain on <code>.where()</code>. </p>
<p>The where method takes three arguments--first, the field that we're searching on an operation, an operator, and then the value on which we want to filter our collection. </p>
<p>We can use any of the following operators and the fields we use can be primitive values as well as arrays.</p>
<p><code>&lt;</code>, <code>&lt;=</code>, <code>==</code>, <code>&gt;</code>, <code>&gt;=</code>, <code>array-contains</code>, <code>in</code>, or <code>array-contains-any</code></p>
<p>To fetch all the users who have submitted more than one book, we can use the following query. </p>
<p>After <code>.where()</code> we need to chain on <code>.get()</code>. Upon resolving our promise we get back what's known as a <strong>querySnapshot</strong>. </p>
<p>Just like getting a collection, we can iterate over the querySnapshot with <code>.map()</code> to get each documents id and data (fields):</p>
<pre><code class="lang-js">firebase
  .firestore()
  .collection(<span class="hljs-string">"users"</span>)
  .where(<span class="hljs-string">"count"</span>, <span class="hljs-string">"&gt;="</span>, <span class="hljs-number">1</span>)
  .get()
  .then(<span class="hljs-function">(<span class="hljs-params">querySnapshot</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> data = querySnapshot.docs.map(<span class="hljs-function">(<span class="hljs-params">doc</span>) =&gt;</span> ({
      <span class="hljs-attr">id</span>: doc.id,
      ...doc.data(),
    }));
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Users with &gt; 1 book: "</span>, data);
    <span class="hljs-comment">// Users with &gt; 1 book:  [ { id: 'user-1', count: 1 } ]</span>
  });
</code></pre>
<blockquote>
<p>Note that you can chain on multiple <code>.where()</code> methods to create compound queries.</p>
</blockquote>
<h3 id="heading-limiting-and-ordering-queries">Limiting and ordering queries</h3>
<p>Another method for effectively querying our collections is to limit them. Let's say we want to limit a given query to a certain amount of documents. </p>
<p>If we only want to return a few items from our query, we just need to add on the <code>.limit()</code> method, after a given reference. </p>
<p>If we wanted to do that through our query for fetching users that have submitted at least one book, it would look like the following. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> usersRef = firebase
  .firestore()
  .collection(<span class="hljs-string">"users"</span>)
  .where(<span class="hljs-string">"count"</span>, <span class="hljs-string">"&gt;="</span>, <span class="hljs-number">1</span>);

  usersRef.limit(<span class="hljs-number">3</span>)
</code></pre>
<p>Another powerful feature is to order our queried data according to document fields using <code>.orderBy()</code>. </p>
<p>If we want to order our created users by when they were first made, we can use the <code>orderBy</code> method with the 'created' field as the first argument. For the second argument, we specify whether it should be in ascending or descending order. </p>
<p>To get all of the users ordered by when they were created from newest to oldest, we can execute the following query:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> usersRef = firebase
  .firestore()
  .collection(<span class="hljs-string">"users"</span>)
  .where(<span class="hljs-string">"count"</span>, <span class="hljs-string">"&gt;="</span>, <span class="hljs-number">1</span>);

  usersRef.orderBy(<span class="hljs-string">"created"</span>, <span class="hljs-string">"desc"</span>).limit(<span class="hljs-number">3</span>);
</code></pre>
<p>We can chain <code>.orderBy()</code> with <code>.limit()</code>. For this to work properly, <code>.limit()</code> should be called last and not before <code>.orderBy()</code>.</p>
<h2 id="heading-want-your-own-copy">Want your own copy?</h2>
<p>If you would like to have this guide for future reference, <a target="_blank" href="https://reedbarger.com/resources/javascript-firestore-2020/">download a cheatsheet of this entire tutorial here</a>. </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://reedbarger.com/resources/javascript-firestore-2020/">https://reedbarger.com/resources/javascript-firestore-2020/</a></div>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The React + Apollo Tutorial for 2020 (Real-World Examples) ]]>
                </title>
                <description>
                    <![CDATA[ If you want to build apps with React and GraphQL, Apollo is the library you should use. I've put together a comprehensive cheatsheet that goes through all of the core concepts in the Apollo library, showing you how to use it with React from front to ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-apollo-client-2020-tutorial/</link>
                <guid isPermaLink="false">66d037b131fbfb6c3390f209</guid>
                
                    <category>
                        <![CDATA[ 2020 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Apollo GraphQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ apollo client ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cheatsheet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GraphQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Sat, 04 Jul 2020 13:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/07/React---Apollo-2020-Cheatsheet.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you want to build apps with React and GraphQL, Apollo is the library you should use.</p>
<p>I've put together a comprehensive cheatsheet that goes through all of the core concepts in the Apollo library, showing you how to use it with React from front to back.</p>
<h3 id="heading-want-your-own-copy">Want Your Own Copy?</h3>
<p>You can grab the PDF cheatsheet <strong><a target="_blank" href="https://reedbarger.com/resources/react-apollo-2020/">right here</a></strong> (it takes 5 seconds).</p>
<p>Here are some quick wins from grabbing the downloadable version:</p>
<ul>
<li>✓ Quick reference to review however and whenever</li>
<li>✓ Tons of useful code snippets based off of real-world projects</li>
<li>✓ Read this guide offline, wherever you like. On the train, at your desk, standing in line — anywhere.</li>
</ul>
<h3 id="heading-prefer-video-lessons">Prefer Video Lessons?</h3>
<p>A great deal of this cheatsheet is based off of the app built in the React + GraphQL 2020 Crash Course. </p>
<p>If you want some more hands-on video lessons, plus see how to build apps with React, GraphQL and Apollo, you can watch the course <a target="_blank" href="https://bit.ly/2020-react-graphql">right here</a>.</p>
<blockquote>
<p>Note: This cheatsheet does assume familiarity with React and GraphQL. If you need a quick refresher on GraphQL and how to write it, a great resource is the <a target="_blank" href="https://graphql.org/learn/">official GraphQL website</a>.</p>
</blockquote>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<h3 id="heading-getting-started">Getting Started</h3>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-apollo-and-why-do-we-need-it">What is Apollo and why do we need it?</a></li>
<li><a class="post-section-overview" href="#heading-apollo-client-basic-setup">Apollo Client setup</a></li>
<li><a class="post-section-overview" href="#heading-creating-a-new-apollo-client-basic-setup">Creating a new Apollo Client</a></li>
<li><a class="post-section-overview" href="#heading-providing-the-client-to-react-components">Providing the client to React components</a></li>
<li><a class="post-section-overview" href="#heading-using-the-client-directly">Using the client directly</a></li>
<li><a class="post-section-overview" href="#heading-writing-graphql-operations-in-js-files-gql">Writing GraphQL in .js files with gql</a></li>
</ul>
<h3 id="heading-core-apollo-react-hooks">Core Apollo React Hooks</h3>
<ul>
<li><a class="post-section-overview" href="#heading-usequery-hook">useQuery Hook</a></li>
<li><a class="post-section-overview" href="#heading-uselazyquery-hook">useLazyQuery Hook</a></li>
<li><a class="post-section-overview" href="#heading-usemutation-hook">useMutation Hook</a></li>
<li><a class="post-section-overview" href="#heading-usesubscription-hook">useSubscription Hook</a></li>
</ul>
<h3 id="heading-essential-recipes">Essential Recipes</h3>
<ul>
<li><a class="post-section-overview" href="#heading-manually-setting-the-fetch-policy">Manually setting the fetch policy</a></li>
<li><a class="post-section-overview" href="#heading-updating-the-cache-upon-a-mutation">Updating the cache upon a mutation</a></li>
<li><a class="post-section-overview" href="#heading-refetching-queries-with-usequery">Refetching queries with useQuery</a></li>
<li><a class="post-section-overview" href="#heading-refetching-queries-with-usemutation">Refetching queries with useMutation</a></li>
<li><a class="post-section-overview" href="#heading-using-the-client-with-useapolloclient">Accessing the client with useApolloClient</a></li>
</ul>
<h3 id="heading-what-is-apollo-and-why-do-we-need-it">What is Apollo and why do we need it?</h3>
<p>Apollo is a library that brings together two incredibly useful technologies used to build web and mobile apps: React and GraphQL. </p>
<p>React was made for creating great user experiences with JavaScript. GraphQL is a very straightforward and declarative new language to more easily and efficiently fetch and change data, whether it is from a database or even from static files. </p>
<p>Apollo is the glue that binds these two tools together. Plus it makes working with React and GraphQL a lot easier by giving us a lot of custom React hooks and features that enable us to both write GraphQL operations and execute them with JavaScript code. </p>
<p>We'll cover these features in-depth throughout the course of this guide.</p>
<h3 id="heading-apollo-client-basic-setup">Apollo Client basic setup</h3>
<p>If you are starting a project with a React template like Create React App, you will need to install the following as your base dependencies to get up and running with Apollo Client:</p>
<pre><code class="lang-bash">// with npm:
npm i @apollo/react-hooks apollo-boost graphql

// with yarn:
yarn add @apollo/react-hooks apollo-boost graphql
</code></pre>
<p><code>@apollo/react-hooks</code> gives us React hooks that make performing our operations and working with Apollo client better</p>
<p><code>apollo-boost</code> helps us set up the client along with parse our GraphQL operations</p>
<p><code>graphql</code> also takes care of parsing the GraphQL operations (along with gql)</p>
<h3 id="heading-apollo-client-subscriptions-setup">Apollo Client + subscriptions setup</h3>
<p>To use all manner of GraphQL operations (queries, mutations, and subscriptions), we need to install more specific dependencies as compared to just <code>apollo-boost</code>:</p>
<pre><code class="lang-bash">// with npm:
npm i @apollo/react-hooks apollo-client graphql graphql-tag apollo-cache-inmemory apollo-link-ws

// with yarn:
yarn add @apollo/react-hooks apollo-client graphql graphql-tag apollo-cache-inmemory apollo-link-ws
</code></pre>
<p><code>apollo-client</code> gives us the client directly, instead of from <code>apollo-boost</code></p>
<p><code>graphql-tag</code> is integrated into <code>apollo-boost</code>, but not included in <code>apollo-client</code></p>
<p><code>apollo-cache-inmemory</code> is needed to setup our own cache (which <code>apollo-boost</code>, in comparison, does automatically)</p>
<p><code>apollo-link-ws</code> is needed for communicating over websockets, which subscriptions require</p>
<h3 id="heading-creating-a-new-apollo-client-basic-setup">Creating a new Apollo Client (basic setup)</h3>
<p>The most straightforward setup for creating an Apollo client is by instantiating a new client and providing just the <code>uri</code> property, which will be your GraphQL endpoint:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> ApolloClient <span class="hljs-keyword">from</span> <span class="hljs-string">"apollo-boost"</span>;

<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> ApolloClient({
  <span class="hljs-attr">uri</span>: <span class="hljs-string">"https://your-graphql-endpoint.com/api/graphql"</span>,
});
</code></pre>
<p><code>apollo-boost</code> was developed in order to make doing things like creating an Apollo Client as easy as possible. What it lacks for the time being, however, is support for GraphQL subscriptions over a websocket connection. </p>
<p>By default, it performs the operations over an http connection (as you can see through our provided uri above).</p>
<p>In short, use <code>apollo-boost</code> to create your client if you only need to execute queries and mutations in your app. </p>
<p>It setups an in-memory cache by default, which is helpful for storing our app data locally. We can read from and write to our cache to prevent having to execute our queries after our data is updated. We'll cover how to do that a bit later.</p>
<h3 id="heading-creating-a-new-apollo-client-subscriptions-setup">Creating a new Apollo Client (+ subscriptions setup)</h3>
<p>Subscriptions are useful for more easily displaying the result of data changes (through mutations) in our app. </p>
<p>Generally speaking, we use subscriptions as an improved kind of query. Subscriptions use a websocket connection to 'subscribe' to updates and data, enabling new or updated data to be immediately displayed to our users without having to reexecute queries or update the cache.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> ApolloClient <span class="hljs-keyword">from</span> <span class="hljs-string">"apollo-client"</span>;
<span class="hljs-keyword">import</span> { WebSocketLink } <span class="hljs-keyword">from</span> <span class="hljs-string">"apollo-link-ws"</span>;
<span class="hljs-keyword">import</span> { InMemoryCache } <span class="hljs-keyword">from</span> <span class="hljs-string">"apollo-cache-inmemory"</span>;

<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> ApolloClient({
  <span class="hljs-attr">link</span>: <span class="hljs-keyword">new</span> WebSocketLink({
    <span class="hljs-attr">uri</span>: <span class="hljs-string">"wss://your-graphql-endpoint.com/v1/graphql"</span>,
    <span class="hljs-attr">options</span>: {
      <span class="hljs-attr">reconnect</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">connectionParams</span>: {
        <span class="hljs-attr">headers</span>: {
          <span class="hljs-attr">Authorization</span>: <span class="hljs-string">"Bearer yourauthtoken"</span>,
        },
      },
    },
  }),
  <span class="hljs-attr">cache</span>: <span class="hljs-keyword">new</span> InMemoryCache(),
});
</code></pre>
<h3 id="heading-providing-the-client-to-react-components">Providing the client to React components</h3>
<p>After creating a new client, passing it to all components is essential in order to be able to use it within our components to perform all of the available GraphQL operations.</p>
<p>The client is provided to the entire component tree using React Context, but instead of creating our own context, we import a special context provider from <code>@apollo/react-hooks</code> called <code>ApolloProvider</code> . We can see how it differs from the regular React Context due to it having a special prop, <code>client</code>, specifically made to accept the created client.</p>
<p>Note that all of this setup should be done in your index.js or App.js file (wherever your Routes declared) so that the Provider can be wrapped around all of your components. </p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { ApolloProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">"@apollo/react-hooks"</span>;

<span class="hljs-keyword">const</span> rootElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>);
ReactDOM.render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ApolloProvider</span> <span class="hljs-attr">client</span>=<span class="hljs-string">{client}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">BrowserRouter</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Switch</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">exact</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">component</span>=<span class="hljs-string">{App}</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">exact</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/new"</span> <span class="hljs-attr">component</span>=<span class="hljs-string">{NewPost}</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">exact</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/edit/:id"</span> <span class="hljs-attr">component</span>=<span class="hljs-string">{EditPost}</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Switch</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">BrowserRouter</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ApolloProvider</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
  rootElement
);
</code></pre>
<h3 id="heading-using-the-client-directly">Using the client directly</h3>
<p>The Apollo client is most important part of the library due to the fact that it is responsible for executing all of the GraphQL operations that we want to perform with React.</p>
<p>We can use the created client directly to perform any operation we like. It has methods corresponding to queries (<code>client.query()</code>), mutations (<code>client.mutate()</code>), and subscriptions (<code>client.subscribe()</code>). </p>
<p>Each method accepts an object and it's own corresponding properties:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// executing queries</span>
client
  .query({
    <span class="hljs-attr">query</span>: GET_POSTS,
    <span class="hljs-attr">variables</span>: { <span class="hljs-attr">limit</span>: <span class="hljs-number">5</span> },
  })
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(err));

<span class="hljs-comment">// executing mutations</span>
client
  .mutate({
    <span class="hljs-attr">mutation</span>: CREATE_POST,
    <span class="hljs-attr">variables</span>: { <span class="hljs-attr">title</span>: <span class="hljs-string">"Hello"</span>, <span class="hljs-attr">body</span>: <span class="hljs-string">"World"</span> },
  })
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(err));

<span class="hljs-comment">// executing subscriptions</span>
client
  .subscribe({
    <span class="hljs-attr">subscription</span>: GET_POST,
    <span class="hljs-attr">variables</span>: { <span class="hljs-attr">id</span>: <span class="hljs-string">"8883346c-6dc3-4753-95da-0cc0df750721"</span> },
  })
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(err));
</code></pre>
<p>Using the client directly can be a bit tricky, however, since in making a request, it returns a promise. To resolve each promise, we either need <code>.then()</code> and <code>.catch()</code> callbacks as above or to <code>await</code> each promise within a function declared with the <code>async</code> keyword.</p>
<h3 id="heading-writing-graphql-operations-in-js-files-gql">Writing GraphQL operations in .js files (gql)</h3>
<p>Notice above that I didn't specify the contents of the variables <code>GET_POSTS</code>, <code>CREATE_POST</code>, and <code>GET_POST</code>. </p>
<p>They are the operations written in the GraphQL syntax which specify how to perform the query, mutation, and subscription respectively. They are what we would write in any GraphiQL console to get and change data.</p>
<p>The issue here, however, is that we can't write and execute GraphQL instructions in JavaScript (.js) files, like our React code has to live in. </p>
<p>To parse the GraphQL operations, we use a special function called a tagged template literal to allow us to express them as JavaScript strings. This function is named <code>gql</code>.</p>
<pre><code class="lang-jsx">
<span class="hljs-comment">// if using apollo-boost</span>
<span class="hljs-keyword">import</span> { gql } <span class="hljs-keyword">from</span> <span class="hljs-string">"apollo-boost"</span>;
<span class="hljs-comment">// else, you can use a dedicated package graphql-tag</span>
<span class="hljs-keyword">import</span> gql <span class="hljs-keyword">from</span> <span class="hljs-string">"graphql-tag"</span>;

<span class="hljs-comment">// query</span>
<span class="hljs-keyword">const</span> GET_POSTS = gql<span class="hljs-string">`
  query GetPosts($limit: Int) {
    posts(limit: $limit) {
      id
      body
      title
      createdAt
    }
  }
`</span>;

<span class="hljs-comment">// mutation</span>
<span class="hljs-keyword">const</span> CREATE_POST = gql<span class="hljs-string">`
  mutation CreatePost($title: String!, $body: String!) {
    insert_posts(objects: { title: $title, body: $body }) {
      affected_rows
    }
  }
`</span>;

<span class="hljs-comment">// subscription</span>
<span class="hljs-keyword">const</span> GET_POST = gql<span class="hljs-string">`
  subscription GetPost($id: uuid!) {
    posts(where: { id: { _eq: $id } }) {
      id
      body
      title
      createdAt
    }
  }
`</span>;
</code></pre>
<h3 id="heading-usequery-hook">useQuery Hook</h3>
<p>The <code>useQuery</code> hook is arguably the most convenient way of performing a GraphQL query, considering that it doesn't return a promise that needs to be resolved.</p>
<p>It is called at the top of any function component (as all hooks should be) and receives as a first required argument—a query parsed with <code>gql</code>.</p>
<p>It is best used when you have queries that should be executed immediately, when a component is rendered, such as a list of data which the user would want to see immediately when the page loads.</p>
<p><code>useQuery</code> returns an object from which we can easily destructure the values that we need. Upon executing a query, there are three primary values will need to use within every component in which we fetch data. They are <code>loading</code>, <code>error</code>, and <code>data</code>.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> GET_POSTS = gql<span class="hljs-string">`
  query GetPosts($limit: Int) {
    posts(limit: $limit) {
      id
      body
      title
      createdAt
    }
  }
`</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { loading, error, data } = useQuery(GET_POSTS, {
    <span class="hljs-attr">variables</span>: { <span class="hljs-attr">limit</span>: <span class="hljs-number">5</span> },
  });

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Error!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> data.posts.map(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Post</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{post.id}</span> <span class="hljs-attr">post</span>=<span class="hljs-string">{post}</span> /&gt;</span></span>);
}
</code></pre>
<p>Before we can display the data that we're fetching, we need to handle when we're loading (when <code>loading</code> is set to true) and we are attempting to fetch the data.</p>
<p>At that point, we display a div with the text 'Loading' or a loading spinner. We also need to handle the possibility that there is an error in fetching our query, such as if there's a network error or if we made a mistake in writing our query (syntax error).</p>
<p>Once we're done loading and there's no error, we can use our data in our component, usually to display to our users (as we are in the example above).</p>
<p>There are other values which we can destructure from the object that <code>useQuery</code> returns, but you'll need <code>loading</code>, <code>error</code>, and <code>data</code> in virtually every component where you execute <code>useQuery</code>. You can see a full list of all of the data we can get back from useQuery <a target="_blank" href="https://www.apollographql.com/docs/react/api/react-hooks/#result">here</a>.</p>
<h3 id="heading-uselazyquery-hook">useLazyQuery Hook</h3>
<p>The <code>useLazyQuery</code> hook provides another way to perform a query, which is intended to be executed at some time after the component is rendered or in response to a given data change.</p>
<p><code>useLazyQuery</code> is very useful for things that happen at any unknown point of time, such as in response to a user's search operation.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Search</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [query, setQuery] = React.useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [searchPosts, { data }] = useLazyQuery(SEARCH_POSTS, {
    <span class="hljs-attr">variables</span>: { <span class="hljs-attr">query</span>: <span class="hljs-string">`%<span class="hljs-subst">${query}</span>%`</span> },
  });
  <span class="hljs-keyword">const</span> [results, setResults] = React.useState([]);

  React.useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (!query) <span class="hljs-keyword">return</span>;
    <span class="hljs-comment">// function for executing query doesn't return a promise</span>
    searchPosts();
    <span class="hljs-keyword">if</span> (data) {
      setResults(data.posts);
    }
  }, [query, data, searchPosts]);

  <span class="hljs-keyword">if</span> (called &amp;&amp; loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> results.map(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">SearchResult</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{result.id}</span> <span class="hljs-attr">result</span>=<span class="hljs-string">{result}</span> /&gt;</span></span>
  ));
}
</code></pre>
<p><code>useLazyQuery</code> differs from <code>useQuery</code>, first of all, in what's returned from the hook. It returns an array which we can destructure, instead of an object.</p>
<p>Since we want to perform this query sometime after the component is mounted, the first element that we can destructure is a function which you can call to perform that query when you choose. This query function is named <code>searchPosts</code> in the example above.</p>
<p>The second destructured value in the array is an object, which we can use object destructuring on and from which we can get all of the same
properties as we did from <code>useQuery</code>, such as <code>loading</code>, <code>error</code>, and <code>data</code>.</p>
<p>We also get an important property named <code>called</code>,
which tells us if we've actually called this function to perform our query.
In that case, if <code>called</code> is true and <code>loading</code> is true, we want to
return "Loading..." instead of our actual data, because are waiting for the data to be returned. This is how <code>useLazyQuery</code> handles fetching data in a synchronous way without any promises.</p>
<p>Note that we again pass any required variables for the query operation as a property, variables, to the second argument. However, if we need, we can pass those variables on an object provided to the query function itself.</p>
<h3 id="heading-usemutation-hook">useMutation Hook</h3>
<p>Now that we know how to execute lazy queries, we know exactly how to work with the <code>useMutation</code> hook. </p>
<p>Like the <code>useLazyQuery</code> hook, it returns an array which we can destructure into its two elements. In the first element, we get back a function, which in this case, we can call it to perform our mutation operation. For next element, we can again destructure an object which returns to us <code>loading</code>, <code>error</code> and <code>data</code>. </p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useMutation } <span class="hljs-keyword">from</span> <span class="hljs-string">"@apollo/react-hooks"</span>;
<span class="hljs-keyword">import</span> { gql } <span class="hljs-keyword">from</span> <span class="hljs-string">"apollo-boost"</span>;

<span class="hljs-keyword">const</span> CREATE_POST = gql<span class="hljs-string">`
  mutation CreatePost($title: String!, $body: String!) {
    insert_posts(objects: { body: $body, title: $title }) {
      affected_rows
    }
  }
`</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">NewPost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [title, setTitle] = React.useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [body, setBody] = React.useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [createPost, { loading, error }] = useMutation(CREATE_POST);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleCreatePost</span>(<span class="hljs-params">event</span>) </span>{
    event.preventDefault();
    <span class="hljs-comment">// the mutate function also doesn't return a promise</span>
    createPost({ <span class="hljs-attr">variables</span>: { title, body } });
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>New Post<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleCreatePost}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(event)</span> =&gt;</span> setTitle(event.target.value)} /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(event)</span> =&gt;</span> setBody(event.target.value)} /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{loading}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>
          Submit
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Unlike with queries, however, we don't use <code>loading</code> or <code>error</code> in order to conditionally render something. We generally use <code>loading</code> in such situations as when we're submitting a form to prevent it being submitted multiple times, to avoid executing the same mutation needlessly (as you can see in the example above). </p>
<p>We use <code>error</code> to display what goes wrong with our mutation to our users. If for example, some required values to our mutation are not provided, we can easily use that error data to conditionally render an error message within the page so the user can hopefully fix what's going wrong.</p>
<p>As compared to passing variables to the second argument of <code>useMutation</code>, we can access a couple of useful callbacks when certain things take place, such as when the mutation is completed and when there is an error. These callbacks are named <code>onCompleted</code> and <code>onError</code>. </p>
<p>The <code>onCompleted</code> callback gives us access to the returned mutation data and it's very helpful to do something when the mutation is done, such as going to a different page. The <code>onError</code> callback gives us the returned error when there is a problem with the mutation and gives us other patterns for handling our errors.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> [createPost, { loading, error }] = useMutation(CREATE_POST, {
  <span class="hljs-attr">onCompleted</span>: <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Data from mutation"</span>, data),
  <span class="hljs-attr">onError</span>: <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error creating a post"</span>, error),
});
</code></pre>
<h3 id="heading-usesubscription-hook">useSubscription Hook</h3>
<p>The useSubscription hook works just like the useQuery hook. </p>
<p>useSubscription returns an object that we can destructure, that includes the same properties, loading, data, and error. </p>
<p>It executes our subscription immediately when the component is rendered. This means we  need to handle loading and error states, and only afterwards display/use our data.  </p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useSubscription } <span class="hljs-keyword">from</span> <span class="hljs-string">"@apollo/react-hooks"</span>;
<span class="hljs-keyword">import</span> gql <span class="hljs-keyword">from</span> <span class="hljs-string">"graphql-tag"</span>;

<span class="hljs-keyword">const</span> GET_POST = gql<span class="hljs-string">`
  subscription GetPost($id: uuid!) {
    posts(where: { id: { _eq: $id } }) {
      id
      body
      title
      createdAt
    }
  }
`</span>;

<span class="hljs-comment">// where id comes from route params -&gt; /post/:id</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PostPage</span>(<span class="hljs-params">{ id }</span>) </span>{
  <span class="hljs-keyword">const</span> { loading, error, data } = useSubscription(GET_POST, {
    <span class="hljs-attr">variables</span>: { id },
    <span class="hljs-comment">// shouldResubscribe: true (default: false)</span>
    <span class="hljs-comment">// onSubscriptionData: data =&gt; console.log('new data', data)</span>
    <span class="hljs-comment">// fetchPolicy: 'network-only' (default: 'cache-first')</span>
  });

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Error!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-keyword">const</span> post = data.posts[<span class="hljs-number">0</span>];

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{post.body}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Just like useQuery, useLazyQuery and useMutation, useSubscription accepts <code>variables</code> as a property provided on the second argument. </p>
<p>It also accepts, however, some useful properties such as <code>shouldResubscribe</code>. This is a boolean value, which will allow our subscription to automatically resubscribe, when our props change. This is useful for when we're passing variables to our you subscription hub props that we know will change. </p>
<p>Additionally, we have a callback function called <code>onSubscriptionData</code>, which enables us to call a function whenever the subscription hook receives new data. Finally, we can set the <code>fetchPolicy</code>, which defaults to 'cache-first'.</p>
<h3 id="heading-manually-setting-the-fetch-policy">Manually Setting the Fetch Policy</h3>
<p>What can be very useful about Apollo is that it comes with its own cache, which it uses to manage the data that we query from our GraphQL endpoint. </p>
<p>Sometimes, however, we find that due to this cache, things aren't updated in the UI in the way that we want. </p>
<p>In many cases we don't, as in the example below, where we are editing a post on the edit page, and then after editing our post, we navigate to the home page to see it in a list of all posts, but we see the old data instead:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// route: /edit/:postId</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">EditPost</span>(<span class="hljs-params">{ id }</span>) </span>{
  <span class="hljs-keyword">const</span> { loading, data } = useQuery(GET_POST, { <span class="hljs-attr">variables</span>: { id } });
  <span class="hljs-keyword">const</span> [title, setTitle] = React.useState(loading ? data?.posts[<span class="hljs-number">0</span>].title : <span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [body, setBody] = React.useState(loading ? data?.posts[<span class="hljs-number">0</span>].body : <span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [updatePost] = useMutation(UPDATE_POST, {
    <span class="hljs-comment">// after updating the post, we go to the home page</span>
    <span class="hljs-attr">onCompleted</span>: <span class="hljs-function">() =&gt;</span> history.push(<span class="hljs-string">"/"</span>),
  });

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleUpdatePost</span>(<span class="hljs-params">event</span>) </span>{
    event.preventDefault();
    updatePost({ <span class="hljs-attr">variables</span>: { title, body, id } });
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleUpdatePost}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(event)</span> =&gt;</span> setTitle(event.target.value)}
        defaultValue={title}
      /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(event)</span> =&gt;</span> setBody(event.target.value)}
        defaultValue={body}
      /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-comment">// route: / (homepage)</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { loading, error, data } = useQuery(GET_POSTS, {
    <span class="hljs-attr">variables</span>: { <span class="hljs-attr">limit</span>: <span class="hljs-number">5</span> },
  });

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Error!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-comment">// updated post not displayed, still see old data</span>
  <span class="hljs-keyword">return</span> data.posts.map(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Post</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{post.id}</span> <span class="hljs-attr">post</span>=<span class="hljs-string">{post}</span> /&gt;</span></span>);
}
</code></pre>
<p>This not only due to the Apollo cache, but also the instructions for what data the query should fetch. We can changed how the query is fetched by using the <code>fetchPolicy</code> property. </p>
<p>By default, the <code>fetchPolicy</code> is set to 'cache-first'. It's going to try to look at the cache to get our data instead of getting it from the network. </p>
<p>An easy way to fix this problem of not seeing new data is to change the fetch policy. However, this approach is not ideal from a performance standpoint, because it requires making an additional request (using the cache directly does not, because it is local data). </p>
<p> There are many different options for the fetch policy listed below:</p>
<pre><code class="lang-jsx">{
  <span class="hljs-attr">fetchPolicy</span>: <span class="hljs-string">"cache-first"</span>; <span class="hljs-comment">// default</span>
  <span class="hljs-comment">/* 
    cache-and-network
    cache-first
    cache-only
    network-only
    no-cache
    standby
  */</span>
}
</code></pre>
<p>I won't go into what each policy does exactly, but to solve our immediate problem, if you always want a query to get the latest data by requesting it from the network, we set <code>fetchPolicy</code> to 'network-first'.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> { loading, error, data } = useQuery(GET_POSTS, {
  <span class="hljs-attr">variables</span>: { <span class="hljs-attr">limit</span>: <span class="hljs-number">5</span> },
  <span class="hljs-attr">fetchPolicy</span>: <span class="hljs-string">"network-first"</span>
});
</code></pre>
<h3 id="heading-updating-the-cache-upon-a-mutation">Updating the cache upon a mutation</h3>
<p>Instead of bypassing the cache by changing the fetch policy of <code>useQuery</code>, let's attempt to fix this problem by manually updating the cache. </p>
<p>When performing a mutation with <code>useMutation</code>. We have access to another callback, known as <code>update</code>. </p>
<p><code>update</code> gives us direct access to the cache as well as the data that is returned from a successful mutation. This enables us to read a given query from the cache, take that new data and write the new data to the query, which will then update what the user sees. </p>
<p>Working with the cache manually is a tricky process that a lot of people tend to avoid, but it's very helpful because it saves some time and resources by not having to perform the same request multiple times to update the cache manually. </p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">EditPost</span>(<span class="hljs-params">{ id }</span>) </span>{
  <span class="hljs-keyword">const</span> [updatePost] = useMutation(UPDATE_POST, {
    <span class="hljs-attr">update</span>: <span class="hljs-function">(<span class="hljs-params">cache, data</span>) =&gt;</span> {
      <span class="hljs-keyword">const</span> { posts } = cache.readQuery(GET_POSTS);
      <span class="hljs-keyword">const</span> newPost = data.update_posts.returning;
      <span class="hljs-keyword">const</span> updatedPosts = posts.map(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span>
        post.id === id ? newPost : post
      );
      cache.writeQuery({ <span class="hljs-attr">query</span>: GET_POSTS, <span class="hljs-attr">data</span>: { <span class="hljs-attr">posts</span>: updatedPosts } });
    },
    <span class="hljs-attr">onCompleted</span>: <span class="hljs-function">() =&gt;</span> history.push(<span class="hljs-string">"/"</span>),
  });

  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>We first want to read the query and get the previous data from it. Then we need to take the new data. In this case, to find the post with a given id and replace it with <code>newPost</code> data, otherwise have it be the previous data, and then write that data back to the same query, making sure that it has the same data structure as before. </p>
<p>After all this, whenever we edit a post and are navigated back to the home page, we should see that new post data.</p>
<h3 id="heading-refetching-queries-with-usequery">Refetching queries with useQuery</h3>
<p>Let's say we display a list of posts using a <code>GET_POSTS</code> query and are deleting one of them with a <code>DELETE_POST</code> mutation.</p>
<p>When a user deletes a post, what do we want to happen?</p>
<p>Naturally, we want it to be removed from the list, both the data and what is displayed to the users. When a mutation is performed, however, the query doesn't know that the data is changed. </p>
<p>There are a few ways of updating what we see, but one approach is to reexecute the query. </p>
<p>We can do so by grabbing the <code>refetch</code> function which we can destructure from the object returned by the <code>useQuery</code> hook and pass it down to the mutation to be executed when it is completed, using the <code>onCompleted</code> callback function:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Posts</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { loading, data, refetch } = useQuery(GET_POSTS);

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> data.posts.map(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Post</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{post.id}</span> <span class="hljs-attr">post</span>=<span class="hljs-string">{post}</span> <span class="hljs-attr">refetch</span>=<span class="hljs-string">{refetch}</span> /&gt;</span></span>
  ));
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Post</span>(<span class="hljs-params">{ post, refetch }</span>) </span>{
  <span class="hljs-keyword">const</span> [deletePost] = useMutation(DELETE_POST, {
    <span class="hljs-attr">onCompleted</span>: <span class="hljs-function">() =&gt;</span> refetch(),
  });

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleDeletePost</span>(<span class="hljs-params">id</span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">window</span>.confirm(<span class="hljs-string">"Are you sure you want to delete this post?"</span>)) {
      deletePost({ <span class="hljs-attr">variables</span>: { id } });
    }
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{post.body}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> handleDeletePost(post.id)}&gt;Delete<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-refetching-queries-with-usemutation">Refetching Queries with useMutation</h3>
<p>Note that we can also utilize the <code>useMutation</code> hook to reexecute our queries through an argument provided to the mutate function, called <code>refetchQueries</code>. </p>
<p>It accepts an array of queries that we want to refetch after a mutation is performed. Each queries is provided within an object, just like we would provide it to client.query(), and consists of a query property and a variables property. </p>
<p>Here is a minimal example to refetch our <code>GET_POSTS</code> query after a new post is created:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">NewPost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [createPost] = useMutation(CREATE_POST, {
    <span class="hljs-attr">refetchQueries</span>: [
      { 
        <span class="hljs-attr">query</span>: GET_POSTS, 
        <span class="hljs-attr">variables</span>: { <span class="hljs-attr">limit</span>: <span class="hljs-number">5</span> } 
      }
    ],
  });

  <span class="hljs-comment">// ...</span>
}
</code></pre>
<h3 id="heading-using-the-client-with-useapolloclient">Using the client with useApolloClient</h3>
<p>We can get access to the client across our components with the help of a special hook called use Apollo client. This execute the hook at the top of our function component and we get back the client itself. </p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Logout</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> client = useApolloClient();
  <span class="hljs-comment">// client is the same as what we created with new ApolloClient()</span>

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLogout</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// handle logging out user, then clear stored data</span>
    logoutUser();
    client.resetStore().then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"logged out!"</span>));
    <span class="hljs-comment">/* Be aware that .resetStore() is async */</span>
  }

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleLogout}</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
}
</code></pre>
<p>And from there we can execute all the same queries, mutations, and subscriptions.</p>
<p>Note that there are a ton more features that come with methods that come with the client. Using the client, we can also write and read data to and from the cache that Apollo sets up (using <code>client.readData()</code> and <code>client.writeData()</code>). </p>
<p>Working with the Apollo cache deserves its own crash course in itself. A great benefit of working with Apollo is that we can also use it as a state management system to replace solutions like Redux for our global state. If you want to learn more about using Apollo to manage global app state you can <a target="_blank" href="https://www.apollographql.com/docs/react/data/local-state/">check out the following link</a>.</p>
<p>I attempted to make this cheatsheet as comprehensive as possible, though it still leaves out many Apollo features that are worth investigating. </p>
<p>If you want to more about Apollo, be sure to check out the <a target="_blank" href="https://www.apollographql.com/docs/react/">official Apollo documentation</a>.</p>
<h3 id="heading-download-the-cheatsheet">Download the cheatsheet</h3>
<p>Want a quick reference of all of these concepts?</p>
<p><a target="_blank" href="https://reedbarger.com/resources/react-apollo-2020/"><img src="https://dev-to-uploads.s3.amazonaws.com/i/7herw99hu78t8gspo88d.png" alt="React and Apollo 2020 Cheatsheet" width="762" height="500" loading="lazy"></a><em>Click to grab the complete PDF cheatsheet</em></p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
