<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: sana</title>
    <description>The latest articles on DEV Community by sana (@sananayab).</description>
    <link>https://dev.to/sananayab</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F804480%2Ffe8ef7f0-0e21-49a6-8463-bc1a8729baf3.png</url>
      <title>DEV Community: sana</title>
      <link>https://dev.to/sananayab</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sananayab"/>
    <language>en</language>
    <item>
      <title>System Design - URL Shorteners</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Sat, 26 Aug 2023 11:31:07 +0000</pubDate>
      <link>https://dev.to/sananayab/system-design-url-shorteners-5hck</link>
      <guid>https://dev.to/sananayab/system-design-url-shorteners-5hck</guid>
      <description>&lt;p&gt;URL shorteners are ubiquitous on the internet, and most of us have encountered them, be it in the form of a shortened YouTube link, a Bitly URL, or a QR code leading us to a website. But have you ever stopped to wonder how these work? Or considered building one yourself?&lt;/p&gt;

&lt;p&gt;What is a URL Shortener?&lt;/p&gt;

&lt;p&gt;A URL shortener is a web service that converts a regular URL into a significantly shorter one that redirects to the original URL. These shorter versions are particularly handy in contexts where character count matters, such as Twitter, or when you want a memorable or neat URL.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;a href="https://www.example.com/very/long/url/structure"&gt;https://www.example.com/very/long/url/structure&lt;/a&gt; might become: &lt;a href="https://short.ly/abcd1234"&gt;https://short.ly/abcd1234&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Why Use a URL Shortener?&lt;/p&gt;

&lt;p&gt;Convenience: They make sharing links easier, especially on platforms with character restrictions.&lt;br&gt;
Readability: They simplify long and complicated URLs.&lt;br&gt;
Analytics: Many URL shortening services provide data on link clicks, the geographic distribution of the audience, referral sources, and more.&lt;br&gt;
Customization: Some services allow custom aliases, turning generic links into branded ones.&lt;br&gt;
The Mechanics of URL Shortening&lt;/p&gt;

&lt;p&gt;At a high level, the process is straightforward:&lt;/p&gt;

&lt;p&gt;The original URL is provided to the shortening service.&lt;br&gt;
The service returns a shorter URL.&lt;br&gt;
When the shorter URL is accessed, the service redirects the user to the original URL.&lt;br&gt;
Now, let's dive into some simple algorithms that can be used for building URL shorteners. These are simple examples, and real-world URL shorteners can be much more complex depending on various usage parameters.&lt;/p&gt;

&lt;p&gt;Hash-Based Shortening&lt;/p&gt;

&lt;p&gt;This is perhaps the most straightforward method. A hash function like MD5 is used to generate a fixed-length hash of the original URL. This hash is then truncated to create a short URL.&lt;/p&gt;

&lt;p&gt;For instance, a simple Java implementation can be:&lt;/p&gt;

&lt;p&gt;byte[] digest = md.digest(longURL.getBytes(StandardCharsets.UTF_8));&lt;br&gt;
StringBuilder sb = new StringBuilder();&lt;/p&gt;

&lt;p&gt;for (int i = 0; i &amp;lt; SHORT_URL_LENGTH; i++) {&lt;br&gt;
    int index = Math.abs(digest[i] % CHARACTERS.length());&lt;br&gt;
    sb.append(CHARACTERS.charAt(index));&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;String shortURL = sb.toString();&lt;br&gt;
Pros:&lt;/p&gt;

&lt;p&gt;Deterministic: The same URL will always produce the same short URL.&lt;br&gt;
Cons:&lt;/p&gt;

&lt;p&gt;Potential for collisions: Different URLs could produce the same hash.&lt;br&gt;
Counter-Based Encoding (Bijective)&lt;/p&gt;

&lt;p&gt;This method usually employs a database. When a URL is submitted, it's stored in the database, and the unique ID from the database is converted into a unique URL-friendly string.&lt;/p&gt;

&lt;p&gt;Pros:&lt;/p&gt;

&lt;p&gt;Collision-free: Each URL gets a unique database ID.&lt;br&gt;
Cons:&lt;/p&gt;

&lt;p&gt;Requires database maintenance.&lt;br&gt;
Character and timestamp Encoding&lt;/p&gt;

&lt;p&gt;A hybrid approach combines random characters and current timestamps. This method generates unique short URLs for each long URL, even if requested within short time intervals.&lt;/p&gt;

&lt;p&gt;For instance, a simple Java implementation can look like:&lt;/p&gt;

&lt;p&gt;long currentTimestamp = System.currentTimeMillis();&lt;br&gt;
StringBuilder sb = new StringBuilder();&lt;br&gt;
Random random = new Random();&lt;/p&gt;

&lt;p&gt;while (sb.length() &amp;lt; SHORT_URL_LENGTH) {&lt;br&gt;
    int index = random.nextInt(CHARACTERS.length());&lt;br&gt;
    sb.append(CHARACTERS[index]);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;String shortURL = sb.toString() + currentTimestamp;&lt;br&gt;
Pros:&lt;/p&gt;

&lt;p&gt;A high degree of uniqueness.&lt;br&gt;
Cons:&lt;/p&gt;

&lt;p&gt;Longer URLs compared to purely hash-based methods. Although the length can be controlled with a possible trade-off on uniqueness.&lt;br&gt;
Real-world Examples&lt;/p&gt;

&lt;p&gt;You must have used one or the other URL shortener in your daily lives. Some of the common URL shorteners available on the internet today are:&lt;/p&gt;

&lt;p&gt;Bitly: Perhaps the most recognized URL shortener, Bitly isn't just about making URLs concise. It's also a powerful marketing tool. Beyond just link shortening, Bitly provides detailed analytics about the audience clicking on their links. Businesses can view the geographical distribution of their audience, understand referrers, and even integrate with other marketing tools.&lt;br&gt;
TinyURL: A venerable veteran in the URL shortening arena, TinyURL made link compression mainstream. It's straightforward to use, and its browser extension means users can instantly shorten a link without needing to visit the TinyURL site. Moreover, TinyURL has ventured into QR codes, allowing users to convert URLs into scannable QR codes.&lt;br&gt;
Google (Goo.gl): Google's foray into URL shortening was widely embraced due to its straightforward nature and integration with other Google products. Though it's now deprecated, Goo.gl was also renowned for its analytics capabilities, providing users with data on click rates, referrer sites, and more.&lt;br&gt;
T2M: T2M goes beyond just shortening URLs. It offers a QR Code service. This feature lets users convert short URLs into QR codes which can be printed on physical products or advertisements, connecting offline consumers to online content.&lt;br&gt;
Ow.ly: Operated by Hootsuite, Ow.ly is particularly popular among social media marketers. It doesn't just truncate URLs; it provides analytics on social media performance, allowing users to track how their links perform across different platforms.&lt;br&gt;
Rebrandly: As the name suggests, Rebrandly lets users create short URLs that can be branded. This means businesses can use their domain names to create trust with their audience. For instance, a pizza chain named "PizzaHot" could use &lt;br&gt;
"PizzaHot.link/offer" as a short URL, making the link recognizable and memorable.&lt;br&gt;
YOURLS: "Your Own URL Shortener" or YOURLS is an open-source and self-hosted URL shortener, allowing tech-savvy users and businesses to run their URL shortening service. This provides them with complete control over the shortening process, data, and analytics.&lt;br&gt;
These real-world examples underscore the versatility and utility of URL shorteners. From simple link reduction for ease of sharing to powerful marketing tools integrated with analytics, URL shorteners have evolved to serve diverse needs in the digital landscape.&lt;/p&gt;

&lt;p&gt;Implementing a URL Shortener&lt;/p&gt;

&lt;p&gt;Creating your URL shortener can be an interesting project, offering both insights into web development and the mechanics of URL shortening. Here’s a comprehensive guide:&lt;/p&gt;

&lt;p&gt;Select an Algorithm: Your choice of algorithm will influence the shortener's efficiency, the likelihood of collisions, and the storage needs. You might opt for a hash-based, counter-based, or character &amp;amp; timestamp encoding approach.&lt;br&gt;
Set Up a Web Service: A framework that will allow you to receive and respond to web requests. For Python enthusiasts, Flask is a minimalistic choice, while Node.js users might prefer Express. Java developers can look towards Spring Boot, and Rubyists have  Sinatra or Rails.&lt;br&gt;
Storage Mechanism:&lt;br&gt;
In-memory storage like dictionaries or HashMaps offer fast access times but lack persistence. Once the server restarts, data could be lost.&lt;br&gt;
Relational databases such as PostgreSQL, MySQL, or SQLite provide persistence and can store additional data, like click counts or creation dates.&lt;br&gt;
NoSQL databases like MongoDB are schema-less and can handle vast amounts of data, offering horizontal scalability.&lt;br&gt;
Handle Collisions: If using hash-based methods, devise a strategy to handle hash collisions. You could:&lt;br&gt;
Check the storage for existing hashes and re-hash until a unique value is found.&lt;br&gt;
Append or prepend a random character or timestamp to the original URL and then hash again.&lt;br&gt;
Implement Redirection: When a user accesses the shortened URL, your server should redirect them to the original URL. This typically involves a 301 Moved Permanently HTTP response.&lt;br&gt;
Analytics (Optional):&lt;br&gt;
Basic: Count the number of clicks for each short URL.&lt;br&gt;
Advanced: Track user agents to identify device types, capture referrers to understand the source of the traffic, and log IP addresses to determine geographical distribution.&lt;br&gt;
Customization &amp;amp; Branding(Optional):&lt;br&gt;
Allow users to customize the path of their shortened URL. Instead of short.ly/abcd1234, they might prefer short.ly/SummerSale.&lt;br&gt;
If your audience includes businesses, consider letting them use custom domains for branding. For instance, Coca-Cola could use coke.link/SummerSale.&lt;br&gt;
Implement Safety Measures:&lt;br&gt;
Rate limiting: To prevent abuse, limit how frequently a user or IP can create short URLs.&lt;br&gt;
Blacklisting: Maintain a list of URLs or domains that are not allowed to be shortened due to malicious content.&lt;br&gt;
Preview Feature: Some shorteners let users preview the destination before redirection, ensuring they aren’t led to potentially harmful sites.&lt;br&gt;
Optimize for Scalability and Performance:&lt;br&gt;
Implement caching mechanisms like Redis to store recently accessed URLs.&lt;br&gt;
If anticipating heavy traffic, consider deploying your application across multiple servers or using a cloud service with auto-scaling.&lt;br&gt;
Extend with APIs: Allow developers to programmatically create or retrieve short URLs. Offering an API can expand the user base and provide integration options with other services.&lt;br&gt;
Frontend Development(Optional):&lt;br&gt;
A user-friendly interface will encourage more users. Implement a clean design with responsive elements for mobile users.&lt;br&gt;
Consider adding features like copying the short URL to the clipboard or displaying QR codes.&lt;br&gt;
Building a URL shortener isn't just about truncating links but also considering user experience, security, scalability, and performance. Whether for personal use, a specific project, or launching a new service, a well-implemented URL shortener can be a valuable digital asset.&lt;/p&gt;

&lt;p&gt;Show Me Some Code&lt;/p&gt;

&lt;p&gt;I have created a simple implementation inspired by the above algorithms which serves as a great starting point for those looking to grasp the mechanics without delving deep into the complexities. This code just generates a short URL without involving the other components like server and databases.&lt;/p&gt;

&lt;p&gt;Features &amp;amp; Highlights&lt;/p&gt;

&lt;p&gt;Open-Source Code: The codebase is freely accessible, allowing enthusiasts and developers to study, modify, and even contribute.&lt;br&gt;
Simplified Approach: For learners or those initiating their journey into distributed systems, this is an excellent place to start. The implementation offers clarity without the clutter of large-scale system intricacies.&lt;br&gt;
Hands-On Learning: Instead of just reading about URL shorteners, you can actively engage, experiment, and even test this system to get a real feel for how URL shortening works in distributed scenarios.&lt;br&gt;
Access &amp;amp; Contribution&lt;/p&gt;

&lt;p&gt;The project is hosted on GitHub and can be accessed here.&lt;/p&gt;

&lt;p&gt;Developers and enthusiasts are encouraged to explore the repository, star it for reference, and even fork it for their experiments.&lt;/p&gt;

&lt;p&gt;Conclusion&lt;/p&gt;

&lt;p&gt;URL shorteners might seem simple on the surface, but as we’ve seen, a lot is going on behind the scenes. Whether you're looking to create your own shortener for a project or simply to understand the magic behind your favourite shortening service, we hope this deep dive has been enlightening.&lt;/p&gt;

&lt;p&gt;Thank you for staying with me so far. Hope you liked the article. You can connect with me on LinkedIn where I regularly discuss technology and life. Also, take a look at some of my other articles and my YouTube channel. Happy reading. 🙂&lt;/p&gt;

</description>
    </item>
    <item>
      <title>React Ecosystem</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Thu, 18 May 2023 16:22:59 +0000</pubDate>
      <link>https://dev.to/sananayab/react-ecosystem-1d4f</link>
      <guid>https://dev.to/sananayab/react-ecosystem-1d4f</guid>
      <description>&lt;p&gt;React is a library for creating user interfaces. It was created in the company Facebook, which gave it to the general public for use. It was quickly accepted by the community and an entire ecosystem began to form around it. The aim of this text is to single out important parts of this ecosystem and to serve as a springboard for further learning for beginners.&lt;/p&gt;

&lt;p&gt;By “React ecosystem” I mean the libraries and tools used in combination with React that I use in my daily work. This does not mean that there are no other alternatives nor that the mode of operation I use is the only correct one.&lt;br&gt;
The story about modern JS applications is roughly like this:&lt;br&gt;
The structure of the application is modular and the modules are usually written in separate files. In order for the modules to communicate with each other, they are imported into other modules and thus a dependency tree is created.&lt;br&gt;
Libraries, or packages, solve one specific problem, or group of problems. Many of the problems we encounter in programming have already been solved. All you have to do is include the appropriate library in your code.&lt;br&gt;
The language specification is evolving faster than browser manufacturers can implement support. In order to use the latest features of JS, it is necessary to translate them in a browser-friendly code before execution. This process is called transpiling.&lt;br&gt;
Since JS applications usually have many different files that are interdependent (JS modules and other resources such as styles and images), they need to be linked and packed into one (or several) files. This process is called bundling. Bundling usually includes various code optimizations, such as minification.&lt;br&gt;
JavaScript is a specific language that people with a different experience often find bad or corrupt in design. My opinion is that it is the unfortunate choice of a name that creates wrong expectations for people in the beginning. JavaScript works the way it is intended, and this is often different from some other languages. In order to use React or any JS framework effectively, you need to know at least the basics of JavaScript.&lt;br&gt;
The best time to start learning JavaScript was yesterday, the second-best time is now. — Paolo Coelho&lt;br&gt;
React is not a framework! Creating larger applications requires a number of other libraries that are used in conjunction with React. Many unknown terms and a large number of different tools can be a problem for beginners in this story. In the following, I will try to define some units in the React ecosystem and single out the tools used in them.&lt;br&gt;
Dependency management&lt;br&gt;
As I mentioned before, React applications are modular. In order to use JS modules, it is necessary to have Node installed. Install Node.&lt;br&gt;
All packages on which the application depends are written in the package.json file. This file contains information about the application, such as name, version, link to the repository, licenses, but also scripts that facilitate the development of the application.&lt;br&gt;
Packages are installed using the npm tool provided with Node, or using the yarn tool, which is the same as npm only slightly differently. This tool makes it easy to install new versions of libraries in use.&lt;br&gt;
User interface&lt;br&gt;
React is in charge of the part of the application that the user sees and with which he can interact, ie the user interface (UI). He is also in charge of propagating each interaction into the inner layers of the application.&lt;br&gt;
The user interface is based on components that encapsulate a single functionality. Components have their own state and a clear interface through which they communicate with other components and other parts of the application.&lt;br&gt;
React uses VirtualDOM which gives it a good performance, and JSX syntax is used to write code, which speeds up application development.&lt;br&gt;
State management&lt;br&gt;
Redux is a predictable container for the state of JS applications. It is a very small library that requires a certain way of writing code that is related to the state of the application.&lt;br&gt;
The state is actually a JS object, which is read-only. Redux imposes a way to modify this object so that all information goes in one direction and does not cause mutations. The change of state is initiated by an action, and the reducer executes the change itself.&lt;br&gt;
Routing&lt;br&gt;
The React router synchronizes the UI with the URL. It allows you to use links in Single Page applications and manage the application in this way.&lt;br&gt;
Testing&lt;br&gt;
Yes is used to write unit tests. It is a tool that has a minimal configuration and immediately after installation it is ready to do what it needs to do. The enzyme is used in combination with Jesta to test the React component.&lt;br&gt;
Thank you for reading.&lt;/p&gt;

</description>
      <category>react</category>
      <category>echosystem</category>
      <category>mernstack</category>
      <category>fullstackdevelopment</category>
    </item>
    <item>
      <title>Create NFT Market Place without any libraries</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Fri, 10 Jun 2022 12:28:51 +0000</pubDate>
      <link>https://dev.to/sananayab/create-nft-market-place-without-any-libraries-3hj9</link>
      <guid>https://dev.to/sananayab/create-nft-market-place-without-any-libraries-3hj9</guid>
      <description>&lt;p&gt;&lt;strong&gt;Create NFT Market Place without any libraries like&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;openZeppelin (part 1)&lt;/p&gt;

&lt;p&gt;Create smart contracts.&lt;/p&gt;

&lt;p&gt;To develop on the blockchain we need a blockchain environment like Truffle&lt;br&gt;
Truffle is the most popular development framework for Ethereum with a mission to make your life a whole lot easier.&lt;/p&gt;

&lt;p&gt;To Install it (I consider you already have npm in your machine) just run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install truffle -g
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;after the truffle is installed successfully, we still need a personal blockchain for Ethereum development that provides us with a development blockchain environment with fake accounts with a 100.00 ETH balance so we can develop contracts and deploy them and run tests.&lt;br&gt;
you can download it easily from here:&lt;br&gt;
&lt;a href="https://trufflesuite.com/ganache/"&gt;https://trufflesuite.com/ganache/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After that install it on your system and open it, then click on QUICKSTART&lt;br&gt;
to start a blockchain (development); you will get&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--c3CGhOee--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qv9twexsqf2x8n3px12g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c3CGhOee--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qv9twexsqf2x8n3px12g.png" alt="Image description" width="880" height="550"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now after we installed the requirements, we need to init our project.&lt;br&gt;
Open the terminal and run:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;truffle int -y&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now, let's take a look at the project structure:&lt;br&gt;
we’ve &lt;strong&gt;truffle-config.js&lt;/strong&gt;&lt;br&gt;
and that's the configuration of our project, let’s make some changes to it, go to the networks and add the network development to work with Ganache,&lt;br&gt;
Ganache works with the following network info:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;develop: {
    host: ‘127.0.0.1’, // Localhost
    port: 7545, // Standard Ethereum port for Ganache
    network_id: ‘5777’, // Ganache network Id
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we named the network develop.&lt;/p&gt;

&lt;p&gt;now we have the test folder to test our contracts and the migrations folder for the contract deployment. and lastly, in the contracts folder that includes the contract files, we’ll find the default file named Integration.sol and that's for the truffle integration, so do not delete it.&lt;/p&gt;

&lt;p&gt;now create a file in the contract folder, name it CreateNFT.sol,&lt;br&gt;
we’ll work with the solidity compiler with the version more than or equal to 0.4.22 and less 0.9.0, just put the following lines:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SPDX-License-Identifier: MIT
pragma solidity &amp;gt;=0.4.22 &amp;lt;0.9.0;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;now create a contract, name it CreateNFT :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SPDX-License-Identifier: MIT
pragma solidity &amp;gt;=0.4.22 &amp;lt;0.9.0;

contract CreateNFT {
    uint256[] private tokensIds;
    mapping(uint256 =&amp;gt; string) private _tokenURIs;

    function createTokenURI(string memory _tokenURI)
        public
        returns (uint256, string memory)
    {
        uint256 currentTokenId = tokensIds.length;
        setTokenURI(currentTokenId, _tokenURI);
        tokensIds.push(currentTokenId++);
        return (currentTokenId, _tokenURI);
    }

    function setTokenURI(uint256 tokenId, string memory _tokenURI) public {
        _tokenURIs[tokenId] = _tokenURI;
    }

    function getTokenURI(uint256 tokenId) public view returns (string memory) {
        string memory _tokenURI = _tokenURIs[tokenId];
        return _tokenURI;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s discuss this file:&lt;/p&gt;

&lt;p&gt;Here we create tokens Ids uint256 array to store them in the blockchain,&lt;/p&gt;

&lt;p&gt;and the same thing about the URIs, but here we created it with the mapping function because of the string type.&lt;br&gt;
Then we three functions two to create the &lt;strong&gt;URI Token&lt;/strong&gt; and the second one is to fetch the token URI by the token id.&lt;br&gt;
the &lt;strong&gt;createTokenURI&lt;/strong&gt; function is a function that we'll create the token for the passed URI, in this function we just decrease the number of the ids and then pass the current id to the next function &lt;strong&gt;setTokenURI&lt;/strong&gt; bypassing the current id and the URI, and it’ll refer the id to the URI, and that’s it.&lt;br&gt;
We can now call to get our URI by passing the id to the last function &lt;strong&gt;getTokenURI(id)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Now let’s call these functions:&lt;/p&gt;

&lt;p&gt;first, we need to deploy our contract:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Go to The migration folder and create a folder, name it &lt;strong&gt;1_nft_creator.js&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;and put the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const TicketNFT = artifacts.require('TicketNFT')
module.exports = function (deployer) {
    deployer.deploy(TicketNFT)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;now run the following command at the root of our project:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;truffle migrate compile-all --reset --network develop
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we’ll migrate then deploy our contract at the network develop (that works with ganache).&lt;br&gt;
if everything goes fine you’ll notice that a new folder created named build;&lt;br&gt;
now our contract has been built, we need now to start development on the blockchain, to do that just run:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;truffle develop&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;now in we need to get an instance for our contract, in the terminal run&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CreateNFT.deployed().then(instance =&amp;gt; app = instance)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--N7qptnmv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hkh45bbh5mh3ujv5u7ps.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--N7qptnmv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hkh45bbh5mh3ujv5u7ps.png" alt="Image description" width="880" height="48"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;get an instance from our contract&lt;/p&gt;

&lt;p&gt;to create a token for a &lt;strong&gt;URI&lt;/strong&gt; just call the **createTokenURI **and pass the URI like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.createTokenURI('https://amirdiafi.com')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the result&lt;br&gt;
after we call the function we created the token and we spent some Gas 🔌&lt;br&gt;
(also when we deployed our contract), as you can see below and created a new block.&lt;/p&gt;

&lt;p&gt;after we call the function we created the token and we spent some Gas 🔌&lt;br&gt;
(also when we deployed our contract), as you can see below and created a new block.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Frnut8Ll--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clnjq9l50balkf9h6767.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Frnut8Ll--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clnjq9l50balkf9h6767.png" alt="Image description" width="880" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and get the TX hash code and the transactionHash, gasUsed ..etc.&lt;br&gt;
now let’s retrieve our URI by passing the token Id:&lt;br&gt;
we know we created just one token so logically we’ve can call it with the &lt;strong&gt;_tokenURIs&lt;/strong&gt;[0]&lt;/p&gt;

&lt;p&gt;now let’s call the function &lt;strong&gt;getTokenURI&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.getTokenURI(0)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and Voila we Got it again.&lt;br&gt;
now we can fetch our data from the IPFS.&lt;/p&gt;

&lt;p&gt;In the next part, we’ll create an NFT market item and pass its data like the pricing, the owner, the seller...etc.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>nft</category>
      <category>machinelearning</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Tips to Become a Better Programmer or Software Developer</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Sun, 05 Jun 2022 10:47:13 +0000</pubDate>
      <link>https://dev.to/sananayab/tips-to-become-a-better-programmer-or-software-developer-5clp</link>
      <guid>https://dev.to/sananayab/tips-to-become-a-better-programmer-or-software-developer-5clp</guid>
      <description>&lt;p&gt;To become a better programmer, you need to be good at the data structure, algorithms, designing using OOP, multi-threading, and various programming concepts like Recursion, divide and conquer, prototyping, and unit testing.&lt;/p&gt;

&lt;p&gt;Programming is a combination of many skills, which means it’s not possible to learn it in a quick time instead, it will come with time and experience, but that won’t happen automatically.&lt;/p&gt;

&lt;p&gt;You can spend five years doing a Java programming job without being a good programmer. Since most Java interviews focus on theory rather than programming and coding skills.&lt;/p&gt;

&lt;p&gt;Not many programmers practice these essential programming skills. If there is a mandatory problem-solving programming test, I will bet the average programmer would have been much better. Anyway, here is my list of things that can help you become a good programmer.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Coding, Coding, and Coding.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Why have I put coding at the top of this list? Because it’s the most difficult and, at the same time, its central piece of programming.&lt;/p&gt;

&lt;p&gt;By doing coding, you also realize your mistakes in designing, error handling, threading, and then go back to those respective skills to improve. You just can not work in designing only; coding produces output, which is vital to learn and act as a success.&lt;/p&gt;

&lt;p&gt;By the way, do not stop just after solving the problem, it’s always better to throw away your first solution, that is just a prototype, your next solution should address issues, missing requirements that you have found building a prototype.&lt;/p&gt;

&lt;p&gt;You can also see this Clean Code course by Maximillian Schwarzmuller for JavaScript developers and Clean Code with Java: Learn Simple Design, Refactoring &amp;amp; TDD course for Java developers to learn more about writing production-quality code which can stand the test of time.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reading Books&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Coding is easier said than done, and there is a massive difference between good code and bad code, but how do you know? You cannot understand the difference until you have seen a good code and know why a particular code is good.&lt;/p&gt;

&lt;p&gt;This is where books come to help; more often than not, authors are great programmers themselves. They offer their experience in the form of a book. I love books, but one book that particularly helped me is Clean Code by Uncle Bob.&lt;/p&gt;

&lt;p&gt;By reading this book, I have found myself finding problems in my code and applying the advice given in this book every now and then. My advice is if you ever find such books, grab them. I also recommend reading these classic books many times and refer them every now and then.&lt;/p&gt;

&lt;p&gt;Another similar book is Effective Java by Joshua Bloch, which is full of good advice. Also, by reading books, you are learning from someone else’s experience, and there are only two ways to improve yourself, either by learning from your own experience (which is very limited) or learning from others’ experience (which is unlimited).&lt;/p&gt;

&lt;p&gt;Remember more is not always good, rather than reading 5 books, I suggest reading two books, which you enjoyed reading multiple times. These two books are also from my list of must-read books for Java programmers.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Practicing Data Structure, Algorithms, and System Design problems
I thought of putting that as the second item, but it ended up third. In my opinion, this is the most critical of things to do to become a better programmer. Most of the good programmers I have seen and met are really good in data structures, algorithms, and Computer Science basics.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By learning these things, you take better advantage of what is available. Since data structure is a key piece of any program, solid knowledge of them helps during problem-solving.&lt;/p&gt;

&lt;p&gt;Similarly, knowledge of key programming principles, search and sorting algorithms, and other well-known algorithms develop programming skills for you.&lt;/p&gt;

&lt;p&gt;You can join a comprehensive course like Data Structure and Algorithms: Deep Dive Using Java to learn more about basic data structure, their properties, and when to use them in your program. It’s one of the better courses I have found on the internet.&lt;/p&gt;

&lt;p&gt;best tips to become a better programmer&lt;/p&gt;

&lt;p&gt;And if you like reading books more than online courses, then you also refer to these books to improve your knowledge of data structure and algorithms.&lt;/p&gt;

&lt;p&gt;Another thing that is crucial to becoming a better developer is to learn about System design and Software architecture. This is one thing that can be the difference between a programmer with 10 years of experience and an experienced programmer.&lt;/p&gt;

&lt;p&gt;You should be familiar with how the system works, how their individual part collaborates, different architectures like Microservices and Monolith, their pros and cons, etc.&lt;/p&gt;

&lt;p&gt;If you need resources, I highly recommend Grokking System Design Interview course on Educative. This interactive course and its second part about advanced design problems can teach you a lot of good things about designing and optimizing a system.&lt;/p&gt;

&lt;p&gt;Grokking the System Design Interview - Learn Interactively&lt;br&gt;
System design questions have become a standard part of the software engineering interview process. Performance in these…&lt;br&gt;
&lt;a href="http://www.educative.io"&gt;www.educative.io&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open Source Contribution
Contributing to the Open source code, especially from Apache, Google, and some other projects is another way to improve your programming skills and become a better programmer. Just signing their mailing list and the following discussion teaches you a lot.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Since most of the discussions happen between good programmers, listening to them and understanding the problem and their approach, solution, and view automatically develops good programming habits.&lt;/p&gt;

&lt;p&gt;To get most of it, do not just sit passive, ask questions, offer your view, but also value others. If you are wondering how to start with open source contribution, then here are some nice articles from Medium to learn about open source contribution&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reading Good Blogs&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Reading good blogs is a small part of reading books. How does reading blogs help you to become a better programmer? Well, it does. Since blogs are often written by programmers themselves, and most of them share their personal views, experience, you often find them relevant.&lt;/p&gt;

&lt;p&gt;Also, blogs are a small piece of information, so it digests well. A blog also helps learn new technology and new features of existing language and API.&lt;/p&gt;

&lt;p&gt;Many times, I have seen something subtle or missed things from a really well-known part of Java described in a small blog post. When it comes to reading good development articles, I prefer to go to websites like Dev.to, FreeCodecamp, and Medium, particularly some dev-focused publications.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reading Code
If reading blogs help to become a good programmer, then reading code help more than that; but at the same time, reading a blog is easy, but reading the code is tough. Do you see resistance? Then you should do it.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Look at the code of open source projects, your fellow programmer’s code, your existing proprietary code, code from Java SDK, and try to understand how they work; try to see what they are doing and why they are doing it.&lt;/p&gt;

&lt;p&gt;Find patterns, develop navigation skills; initially, you will find it boring and difficult, but with time you will develop a good code sense, which will alert you when you make a mistake, help you spot others’ mistakes, gaps, and code smell.&lt;/p&gt;

&lt;p&gt;This Code sense is one of the signs of a better programmer, they often tend to look, at what you missed.&lt;/p&gt;

&lt;p&gt;best tips to become a better coder&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Writing Unit tests
The unit test complements the thinking and coding process and subsequently helps you to design better. Anything difficult to test has a chance of improvement. Also, writing unit tests helps a lot in finding better names, better abstraction, better interface, abstract class design, and overall improves code quality.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But like coding and designing, unit testing is also a tough job for average programmers, you will see a lot of resistance there. Some programmer writes trivial test instead of thinking hard about usage scenario.&lt;/p&gt;

&lt;p&gt;Remember, there is no substitute for thinking through the process, after analysis, design, and development, unit testing is another opportunity to think through scenarios and gaps in your code. Make it a rule; always write a Unit test for your code.&lt;/p&gt;

&lt;p&gt;If you want to learn Unit testing in Java, I suggest you learn JUnit and Mockito, two essential frameworks for unit testing in Java, and if you need a course, I suggest you join the JUnit 5 in 20 steps course by Ranga Karnan on Udemy.&lt;/p&gt;

&lt;p&gt;best tips to become a better developer&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Doing Code reviews
Like Unit testing, Code review is another development practice that helps to become a good solid programmer. Code review helps both reviewer and author; the reviewer improves his code sense and offers genuine advice while the author learns from his mistakes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;It often helps that the code you think is rock solid has some bugs which only other programmers can see, Code review and four eye check does that for you.&lt;/p&gt;

&lt;p&gt;If you are lucky and get a chance to work in a company that has unit testing, code review as a discipline, then you are likely to be a better programmer than the rest. These two things immensely help to improve programming skills.&lt;/p&gt;

&lt;p&gt;If you are wondering what to check on Code reviews, I suggest you check if the code is functionally correct, if standard practices have been followed like SOLID design principles and Java naming conventions. Another thing you can check is if there are enough unit tests or not, which are often neglected.&lt;/p&gt;

&lt;p&gt;Note— Don’t do the code review in a big company style as the great Joma does&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Talking to a fellow programmer
Reading is a passive event compared to talking. Talking about a program and discussing that with a fellow programmer often leads to a better solution; it’s natural because your mind tends to involve more when you talk and listen to others.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I found gaps, missing requirements, bugs, and design flaws while discussing with teammates. In the software industry, where programmers tend to isolate themselves with their computers, talking, sharing, and doing whiteboard sessions helps immensely.&lt;/p&gt;

&lt;p&gt;Don’t just sit and code, talk, listen, think, and hang out with fellow programmers. Participating in the event also helps. You may also get some useful and practice tips to become a better developer overnight, like this one :-)&lt;/p&gt;

&lt;p&gt;best tips to become a better software engineer programmer&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Participating in Stack Overflow and forums, Commenting on Blogs
This is another form of activity which helps you to revise knowledge. By sharing knowledge, the first person who benefits is the one who shares. Since programming is vast, you tend to forget most things you don’t use for more than three months.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Participating in StackOverflow and, answering others’ queries, commenting on blogs and forums is a nice little way to revise knowledge and correct your misconception.&lt;/p&gt;

&lt;p&gt;By putting our knowledge in front of others, we help others and put them to the test. Many times you will see someone benefiting from your knowledge, but also you are getting your misconception corrected.&lt;/p&gt;

&lt;p&gt;Every programmer wants to become a better programmer, but not everyone succeeds. Apart from the natural talent of programming and problem solving, it requires a lot of hard work, constant learning, and perseverance to become a better programmer.&lt;/p&gt;

&lt;p&gt;The more you do real work like coding, design, Unit Testing, and Code review, you will become better. If you just want to do one thing at this moment, I would say go and read clean code.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>React: How to Fetch Data From API</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Sat, 26 Mar 2022 03:57:42 +0000</pubDate>
      <link>https://dev.to/sananayab/react-how-to-fetch-data-from-api-1a1b</link>
      <guid>https://dev.to/sananayab/react-how-to-fetch-data-from-api-1a1b</guid>
      <description>&lt;p&gt;When making user interfaces, we often need to fetch data from an API. For example, in an e-commerce site, the products will be fetched from an API, the data we fetch will include product images, prices, names, comments, etc.&lt;/p&gt;

&lt;p&gt;In this article, I’ll cover how to fetch data from an API. I’ll build a very basic app where I fetch harry potter characters from an API, so let’s jump right into it.&lt;br&gt;
&lt;strong&gt;1-Create the base of our App&lt;/strong&gt;&lt;br&gt;
Basically what we want is to show random Harry Potter characters when the page is loaded. So, let’s build a skeleton app for that.&lt;/p&gt;

&lt;p&gt;Create a react app with create-react-app and create a Character component :&lt;/p&gt;

&lt;p&gt;&lt;em&gt;src/Character.js&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import styled from 'styled-components';

const Character = ({
    imageURL,
    name
}) =&amp;gt; {
    return (
        &amp;lt;Wrapper&amp;gt;
            &amp;lt;Image src={imageURL} /&amp;gt;
            &amp;lt;Text&amp;gt;{name}&amp;lt;/Text&amp;gt;
        &amp;lt;/Wrapper&amp;gt;
    )
}

const Wrapper = styled.div`
border-radius:1rem;
padding:1rem;
border:2px solid black;
display:flex;
flex-flow:column nowrap;
width:20rem;
height:20rem;

`
const Image = styled.img`
width:auto;
height:85%;
object-fit:contain;
`

const Text = styled.div`
padding:0.5rem;
font-size:1.25rem;
`
export default Character

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this project, I’ve used styled components for styling, to learn more about them, checkout : &lt;a href="https://smilepk145.medium.com/how-to-use-styled-components-in-react-ed609c49a6d6"&gt;https://smilepk145.medium.com/how-to-use-styled-components-in-react-ed609c49a6d6&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And to try out our Character component, go to App.js and modify it like this :&lt;/p&gt;

&lt;p&gt;src/App.js&lt;br&gt;
We’ve used mock data to try out the Character component and the output is this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4C1GR05r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywvevh4mneq8tmeuo1n8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4C1GR05r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywvevh4mneq8tmeuo1n8.png" alt="Image description" width="407" height="402"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I think it’s good enough for our example project. So, let’s try to fetch some characters from an API and create characters dynamically.&lt;/p&gt;

&lt;p&gt;2-Fetch data from an API&lt;/p&gt;

&lt;p&gt;For fetching data, you can use many alternative libraries. My choice is using axios library. It’s the most popular library for fetching data. To install axios, put the below code into the terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install axios
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And after installing axios modify App.js file like below:&lt;/p&gt;

&lt;p&gt;src/App.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect } from 'react';
import styled from 'styled-components';
import axios from 'axios';

const App = () =&amp;gt; {
  useEffect(() =&amp;gt; {
    const getCharacters = async function () {
      const baseURL = "&amp;lt;http://hp-api.herokuapp.com/api/characters&amp;gt;";
      const response = await axios.get(baseURL);
      const data = response.data;
      console.log("data", data);
    }
    getCharacters();
  }, [])

  return (
    &amp;lt;AppWrapper&amp;gt;

    &amp;lt;/AppWrapper&amp;gt;
  )
}
const AppWrapper = styled.div`
width:100%;
height:100%;
display:flex;
flex-flow:row wrap;
justify-content:space-evenly;
align-items:center;
`

export default App

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Basically, we used&lt;code&gt;useEffect&lt;/code&gt; hook to fetch data when the app first loads.&lt;/p&gt;

&lt;p&gt;In** getCharacters** function, we sent a get request to API using baseURL. And then the API returns a response. &lt;strong&gt;console.log(”data”,data)’&lt;/strong&gt;s output is like below:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--aGlxejB_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y7xs4mdo5ybtzlutrlep.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--aGlxejB_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y7xs4mdo5ybtzlutrlep.png" alt="Image description" width="480" height="185"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see, the data is an array of objects, each object has information about a &lt;strong&gt;character&lt;/strong&gt;. Let’s try to show 4 random characters with our Character component. Modify the &lt;code&gt;App.js&lt;/code&gt; like below:&lt;/p&gt;

&lt;p&gt;src/App.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import Character from './Character';

const App = () =&amp;gt; {
  const [characters, setCharacters] = useState([]);
  useEffect(() =&amp;gt; {
    const getCharacters = async function () {
      const baseURL = "&amp;lt;http://hp-api.herokuapp.com/api/characters&amp;gt;";
      const response = await axios.get(baseURL);
            /*filter the data this time, because some data doesn't have image and we
            need an image for each character*/
      const data = response.data.filter(char =&amp;gt; char.image);
      console.log("data", data);
      let fourRandomCharacters = [];
      for (let i = 0; i &amp;lt; 4; i++) {
        const index = Math.floor(Math.random() * data.length);
        fourRandomCharacters.push(data[index]);
      }
            //set characters to characters state
      setCharacters(fourRandomCharacters);
    }
    getCharacters();
  }, [])

  return (
    &amp;lt;AppWrapper&amp;gt;
      {characters.map((character, index) =&amp;gt;
        &amp;lt;Character
          key={index}
          imageURL={character.image}
          name={character.name}
        /&amp;gt;
      )}
    &amp;lt;/AppWrapper&amp;gt;
  )
}
const AppWrapper = styled.div`
width:100%;
height:100%;
display:flex;
flex-flow:row wrap;
justify-content:space-evenly;
align-items:center;
`
export default App
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This time we filtered the returned data because some data doesn’t have images. After that, we stored the 4 characters in a React state using useState hook. And we used Array.map method to render all 4 characters from state.&lt;/p&gt;

&lt;p&gt;And the output looks like this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Wd5UX0Cy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjomzuvh9zregg12zuo9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Wd5UX0Cy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjomzuvh9zregg12zuo9.png" alt="Image description" width="772" height="617"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_d2XeN5y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0cvqky64nb8yddhnfj8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_d2XeN5y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0cvqky64nb8yddhnfj8.png" alt="Image description" width="772" height="617"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xTGCzQXq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/horhew2y5erldmgonke9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xTGCzQXq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/horhew2y5erldmgonke9.png" alt="Image description" width="772" height="617"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9loZ2o85--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzox8rzi1s832rchy6n2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9loZ2o85--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzox8rzi1s832rchy6n2.png" alt="Image description" width="772" height="617"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Summary:&lt;/p&gt;

&lt;p&gt;When fetching data from an API in React, we send a get request to the API, modify the returned data according to our needs and use that data in our app.&lt;/p&gt;

&lt;p&gt;This is it for this article, I hope you enjoyed and learned a lot.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to Manage State in Your React Apps</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Wed, 23 Mar 2022 13:42:38 +0000</pubDate>
      <link>https://dev.to/sananayab/how-to-manage-state-in-your-react-apps-4n67</link>
      <guid>https://dev.to/sananayab/how-to-manage-state-in-your-react-apps-4n67</guid>
      <description>&lt;p&gt;Managing state in your React apps isn’t as simple as using &lt;code&gt;useState&lt;/code&gt; or &lt;code&gt;useReducer&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Not only are there are a lot of different kinds of state, but there often dozens of ways of managing each kind. Which should you choose?&lt;/p&gt;

&lt;p&gt;In this guide, we will uncover the several kinds of state in your React apps that you might not be aware of, plus how to manage them in the most effective way.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Four Kinds of React State to Manage&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When we talk about state in our applications, it’s important to be clear about what types of state actually matter.&lt;/p&gt;

&lt;p&gt;There are four main types of state you need to properly manage in your React apps:&lt;/p&gt;

&lt;p&gt;Local state&lt;br&gt;
Global state&lt;br&gt;
Server state&lt;br&gt;
URL state&lt;br&gt;
Let's cover each of these in detail:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Local (UI) state&lt;/strong&gt; – Local state is data we manage in one or another component.&lt;/p&gt;

&lt;p&gt;Local state is most often managed in React using the &lt;code&gt;useState&lt;/code&gt; hook.&lt;/p&gt;

&lt;p&gt;For example, local state would be needed to show or hide a modal component or to track values for a form component, such as form submission, when the form is disabled and the values of a form’s inputs.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Global (UI) state *&lt;/em&gt;– Global state is data we manage across multiple components.&lt;/p&gt;

&lt;p&gt;Global state is necessary when we want to get and update data anywhere in our app, or in multiple components at least.&lt;/p&gt;

&lt;p&gt;A common example of global state is authenticated user state. If a user is logged into our app, it is necessary to get and change their data throughout our application.&lt;/p&gt;

&lt;p&gt;Sometimes state we think should be local might become global.&lt;/p&gt;

&lt;p&gt;Server state – Data that comes from an external server that must be integrated with our UI state.&lt;/p&gt;

&lt;p&gt;Server state is a simple concept, but can be hard to manage alongside all of our local and global UI state.&lt;/p&gt;

&lt;p&gt;There are several pieces of state that must be managed every time you fetch or update data from an external server, including loading and error state.&lt;/p&gt;

&lt;p&gt;Fortunately there are tools such as SWR and React Query that make managing server state much easier.&lt;/p&gt;

&lt;p&gt;URL state – Data that exists on our URLs, including the pathname and query parameters.&lt;/p&gt;

&lt;p&gt;URL state is often missing as a category of state, but it is an important one.&lt;br&gt;
In many cases, a lot of major parts of our application rely upon accessing URL state. Try to imagine building a blog without being able to fetch a post based off of its slug or id that is located in the URL!&lt;/p&gt;

&lt;p&gt;There are undoubtedly more pieces of state that we could identify, but these are the major categories worth focusing on for most applications you build.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to Manage Local State in React&lt;/strong&gt;&lt;br&gt;
Local state is perhaps the easiest kind of state to manage in React, considering there are so many tools built into the core React library for managing it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useState&lt;/code&gt; is the first tool you should reach for to manage state in your components.&lt;/p&gt;

&lt;p&gt;It can take accept any valid data value, including primitive and object values. Additionally, its setter function can be passed down to other components as a callback function (without needing optimizations like &lt;code&gt;useCallback&lt;/code&gt;).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from "react";

function Layout() {
  const [isSidebarOpen, setSidebarOpen] = useState(false);

  return (
    &amp;lt;&amp;gt;
      &amp;lt;Sidebar isSidebarOpen={isSidebarOpen} closeSidebar={() =&amp;gt; setSidebarOpen(false)} /&amp;gt;
      {/* ... */}
    &amp;lt;/&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;useReducer&lt;/code&gt; is another option that can be used for either local or global state. It is similar in many ways to &lt;code&gt;useState&lt;/code&gt; under the hood, although instead of just an initial state it accepts a reducer.&lt;/p&gt;

&lt;p&gt;The benefit of &lt;code&gt;useReducer&lt;/code&gt;is that it provides a built-in way to perform a number of different state operations with the help of the &lt;code&gt;reducer&lt;/code&gt;function, which makes it more dynamic overall than &lt;code&gt;useState&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You can see the benefit of &lt;code&gt;useReducer&lt;/code&gt; versus &lt;code&gt;useState&lt;/code&gt; in this vote tracking example. All we have to do to update state is pass the callback function &lt;code&gt;dispatch&lt;/code&gt; a string (which is then passed to the reducer) instead of the new state itself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initialState = { votes: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'upvote':
      return {votes: state.votes + 1};
    case 'downvote':
      return {votes: state.votes - 1};
    default:
      throw new Error();
  }
}

function VoteCounter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    &amp;lt;&amp;gt;
      Current Votes: {state.votes}
      &amp;lt;button onClick={() =&amp;gt; dispatch({type: 'upvote'})}&amp;gt;Upvote&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({type: 'downvote'})}&amp;gt;Downvote&amp;lt;/button&amp;gt;
    &amp;lt;/&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How to Manage Global State in React&lt;/strong&gt;&lt;br&gt;
Once you attempt to manage state across multiple components, things get a bit trickier.&lt;/p&gt;

&lt;p&gt;You will reach a point in your application where patterns like “lifting state up” and passing callbacks down to update your state from components lead to lots and lots of props.&lt;/p&gt;

&lt;p&gt;What do you do if you want to update a component’s state from basically anywhere in your app? You turn it into global state.&lt;/p&gt;

&lt;p&gt;To manage it, however, you should opt for a third-party solution. Many developers are inclined to use built-in React features like the Context API to manage their state.&lt;/p&gt;

&lt;p&gt;To be clear: the Context API is not a state management solution. It is a way to avoid problems like props drilling (creating a bunch of props in components that don’t need it), but it is only helpful for reading state, not updating it.&lt;br&gt;
The reason to not use Context for global state management lies in the way it works. The default behavior for Context is to re-render all children components if the value provided to it as a prop changes.&lt;/p&gt;

&lt;p&gt;For example, it is bad practice to combine &lt;code&gt;useReducer&lt;/code&gt; and &lt;code&gt;useContext&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    &amp;lt;StateProvider.Provider value={{ state, dispatch }}&amp;gt;
      &amp;lt;ComponentA /&amp;gt;
      &amp;lt;ComponentB /&amp;gt;
      &amp;lt;ComponentC /&amp;gt;
    &amp;lt;/StateProvider.Provider&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In many cases, you do not want all children to update in response to a global state update, because all children may not be consuming or relying upon that global state. You only want to re-render if their props or state changes.&lt;/p&gt;

&lt;p&gt;To manage your global state, reach for tried and tested third-party libraries like Zustand, Jotai, and Recoil.&lt;br&gt;
zustand jotai&lt;/p&gt;

&lt;p&gt;Zustand, Jotai and Redux Toolkit Libraries&lt;br&gt;
Redux is also great, but make sure that you get started using Redux Toolkit.&lt;/p&gt;

&lt;p&gt;The benefit of a library like Zustand is that it is small, makes your entire global state a custom hook, and to read or update state, you just call this hook in your components.&lt;/p&gt;

&lt;p&gt;To use Zustand, &lt;code&gt;run npm install zustand&lt;/code&gt;. After that, make a dedicated store file or folder and create your store:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import create from 'zustand'

const useStore = create(set =&amp;gt; ({
  votes: 0,
  upvote: () =&amp;gt; set(state =&amp;gt; ({ vote: state.votes + 1 })),
  downvote: () =&amp;gt; set(state =&amp;gt; ({ vote: state.votes - 1 })),
}))

function VoteCounter() {
  const { votes, upvote, downvote } = useStore();

  return (
    &amp;lt;&amp;gt;
      Current Votes: {votes}
      &amp;lt;button onClick={upvote}&amp;gt;Upvote&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={downvote}&amp;gt;Downvote&amp;lt;/button&amp;gt;
    &amp;lt;/&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One large reason I recommend using Zustand over a library like Redux is that it gives you all the functionality you need without the boilerplate and conceptual overhead of actions, reducers, and so on.&lt;/p&gt;

&lt;p&gt;Plus, you don’t need to wrap your components in a Context Provider. Just install and go!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to Manage Server State in React&lt;/strong&gt;&lt;br&gt;
Server state can be deceptively challenging to manage.&lt;/p&gt;

&lt;p&gt;At first, it seems you just need to fetch data and display it in the page. But then you need to display a loading spinner while you are waiting for the data. Then you need to handle errors and display them to the user as they arise.&lt;/p&gt;

&lt;p&gt;What happens when there is a network error? Do I really need to hit my server every time my user visits the home page if the data hasn’t changed? Do I need to add &lt;code&gt;useState&lt;/code&gt; and &lt;code&gt;useEffect&lt;/code&gt; in every component I want to fetch my data?&lt;/p&gt;

&lt;p&gt;To fix this, there are a couple of great libraries that make data fetching in React a breeze: &lt;strong&gt;SWR&lt;/strong&gt; and &lt;strong&gt;React Query&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SWR and React Query Libraries&lt;/strong&gt;&lt;br&gt;
They not only give us a convenient hook to both get and change data from an API, but they keep track of all the necessary states and cache the data for us.&lt;/p&gt;

&lt;p&gt;Here is an example of fetching a user’s profile from an API on the client. We call &lt;code&gt;useSWR&lt;/code&gt; and specify the endpoint from which to request data, which is passed to our &lt;code&gt;fetcher&lt;/code&gt; function and &lt;code&gt;useSWR&lt;/code&gt; gives us both &lt;code&gt;data&lt;/code&gt; and &lt;code&gt;error&lt;/code&gt; state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import useSWR from 'swr'

const fetcher = url =&amp;gt; fetch(url).then(r =&amp;gt; r.json())

function User() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return &amp;lt;div&amp;gt;failed to load&amp;lt;/div&amp;gt;
  if (!data) return &amp;lt;div&amp;gt;loading...&amp;lt;/div&amp;gt;

  return &amp;lt;div&amp;gt;hello {data.name}!&amp;lt;/div&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;SWR makes managing unsuccessful requests much easier and our components a lot nicer to look at.&lt;/p&gt;

&lt;p&gt;Additionally, if you are performing the same operation over and over again, you use &lt;code&gt;useSWR&lt;/code&gt; in your own custom hook to reuse across your app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function useUser (id) {
  const { data, error } = useSWR(`/api/user/${id}`, fetcher)

  return {
    user: data,
    isLoading: !error &amp;amp;&amp;amp; !data,
    isError: error
  }
}

function Avatar ({ id }) {
  const { user, isLoading, isError } = useUser(id)

  if (isLoading) return &amp;lt;Spinner /&amp;gt;
  if (isError) return &amp;lt;Error /&amp;gt;

  return &amp;lt;img src={user.avatar} /&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And finally, you can provide global options to &lt;code&gt;useSWR&lt;/code&gt;, including your&lt;code&gt;fetcher&lt;/code&gt; function (so you don’t need to pass it in every time) as well as a number of times to refetch data again after an error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import useSWR, { SWRConfig } from 'swr'

function Admin () {
  // no need to pass in the fetcher function
  const { data: courses } = useSWR('/api/courses')
  const { data: orders } = useSWR('/api/orders')
  const { data: users } = useSWR('/api/users')

  // ...
}

function App () {
  return (
    &amp;lt;SWRConfig 
      value={{
        errorRetryCount: 2, 
        errorRetryInterval: 5000,
        fetcher: (resource, init) =&amp;gt; fetch(resource, init).then(res =&amp;gt; res.json())
      }}
    &amp;gt;
      &amp;lt;Admin /&amp;gt;
    &amp;lt;/SWRConfig&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is just a taste of the benefits of the SWR library, and React Query gives you just as many benefits, if not more.&lt;/p&gt;

&lt;p&gt;Be sure to use either one for managing your server state. It will make your life so much easier.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to Manage URL State in React&lt;/strong&gt;&lt;br&gt;
To end a difficult topic on a positive note, URL state is largely already managed for you if you are using a framework like Next.js or the current version of React Router.&lt;/p&gt;

&lt;p&gt;URL state is quite easy to manage, usually through custom hooks that give us all the information we need about our location, history, and pathname.&lt;/p&gt;

&lt;p&gt;If you are using React Router, you can get all the information you need using &lt;code&gt;useHistory&lt;/code&gt;or useLocation``.&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;br&gt;
import { useHistory, useLocation } from 'react-router-dom';&lt;/p&gt;

&lt;p&gt;function BlogPost() {&lt;br&gt;
  const history = useHistory();&lt;br&gt;
    console.log("you are here: ", history.location);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const location = useLocation();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;console.log('your pathname is: , location.pathname);&lt;/p&gt;

&lt;p&gt;// ...&lt;br&gt;
}&lt;br&gt;
&lt;code&gt;&lt;/code&gt;&lt;code&gt;&lt;br&gt;
Additionally, if you have any route parameters that you need to use, for example to fetch data based off of, you can use the&lt;/code&gt;useParams` hook.&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;br&gt;
import { useParams } from 'react-router-dom';&lt;/p&gt;

&lt;p&gt;function ChatRoom() {&lt;br&gt;
  const { roomId } = useParams();&lt;br&gt;
  const { chatRoom, isLoading, isError } = useChatRoom(roomId);&lt;/p&gt;

&lt;p&gt;// ...&lt;br&gt;
}&lt;br&gt;
If you are using Next.js, almost everything can access directly from calling useRouter.&lt;/p&gt;

&lt;p&gt;function Orders() {&lt;br&gt;
  const router = useRouter();&lt;br&gt;
  console.log('the entire url is: ', router.asPath);&lt;br&gt;
  console.log('your current route is: ', router.pathname);&lt;br&gt;
  console.log('your query params are: ', router.query);&lt;/p&gt;

&lt;p&gt;function handleSubmit(item) {&lt;br&gt;
    setQuery("");&lt;br&gt;
    // push to new route&lt;br&gt;
    router.push(item.href);&lt;br&gt;
    closeDropdown();&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;// ...&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
    </item>
    <item>
      <title>React State for Beginners</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Tue, 22 Mar 2022 04:50:38 +0000</pubDate>
      <link>https://dev.to/sananayab/react-state-for-beginners-b0k</link>
      <guid>https://dev.to/sananayab/react-state-for-beginners-b0k</guid>
      <description>&lt;p&gt;One of the most essential concepts that any modern JavaScript developer needs to understand is state.&lt;/p&gt;

&lt;p&gt;If you don't understand state, you're not going to be able to fully use and take advantage of powerful libraries such as React to build your applications.&lt;/p&gt;

&lt;p&gt;Let's see exactly what state is, how it already exists in your JavaScript applications now, and how React allows us to much more easily manage it with built-in hooks like &lt;code&gt;useState&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is state?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Something that may surprise you is that any website or application you build with plain JavaScript already involves state. It's just not obvious where it lives.&lt;/p&gt;

&lt;p&gt;Here is a basic example:&lt;/p&gt;

&lt;p&gt;Let's say that we're building a counter application with JavaScript. We want this application to be able to display the current count as well as increase and decrease the count by one.&lt;/p&gt;

&lt;p&gt;It will consist of just the current count as well as a button to increase the count by one and another to decrease the count by one.&lt;/p&gt;

&lt;p&gt;This is what the final version of our app will look like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1xXoD_FX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7recumd7fbphfbillyin.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1xXoD_FX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7recumd7fbphfbillyin.gif" alt="Image description" width="545" height="336"&gt;&lt;/a&gt;&lt;br&gt;
Here is the starting markup for our application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Counter App&amp;lt;/title&amp;gt;
    &amp;lt;meta charset="UTF-8" /&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;button&amp;gt;+ 1&amp;lt;/button&amp;gt;
      &amp;lt;span&amp;gt;0&amp;lt;/span&amp;gt;
      &amp;lt;button&amp;gt;- 1&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Simply put, &lt;strong&gt;state is data that we need to manage over time within our application&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;State is often changed through user input and that is the case within our application here.&lt;/p&gt;

&lt;p&gt;What is the state in our counter app? It is the count number.&lt;/p&gt;

&lt;p&gt;Our user can increase or decrease the state value by clicking on the appropriate button. What's important is that we want to display those changes to our user.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problems with state in plain JavaScript&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While state seems like a simple concept, there are two    problems with managing it when you use plain JavaScript alone:&lt;/p&gt;

&lt;p&gt;1 It is not obvious what the state is or where it lives.&lt;/p&gt;

&lt;p&gt;2 Reading and updating the state is an unnatural and often &lt;br&gt;
    repetitive process when using native browser APIs like &lt;br&gt;
     document.&lt;br&gt;
How would we go about updating our count state when our user clicks on either button?&lt;/p&gt;

&lt;p&gt;We first need to get a reference to each element. To do this in plain JavaScript, it is common practice to add a unique &lt;code&gt;id&lt;/code&gt; attribute to each element, select each element in JavaScript with the &lt;code&gt;document.querySelector&lt;/code&gt; method, and store the reference in a local variable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Counter App&amp;lt;/title&amp;gt;
    &amp;lt;meta charset="UTF-8" /&amp;gt;
  &amp;lt;/head&amp;gt;

  &amp;lt;body&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;button id="increment"&amp;gt;+ 1&amp;lt;/button&amp;gt;
      &amp;lt;span id="count"&amp;gt;0&amp;lt;/span&amp;gt;
      &amp;lt;button id="decrement"&amp;gt;- 1&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;

    &amp;lt;script&amp;gt;
      const increment = document.querySelector("#increment");
      const count = document.querySelector("#count");
      const decrement = document.querySelector("#decrement");
    &amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have references to every HTML element, how do we make the increment button work?&lt;/p&gt;

&lt;p&gt;We first need to listen for a click event on our increment button. Then, when the button is clicked, we need to get the current count value from the element with the &lt;code&gt;id&lt;/code&gt; of "count".&lt;/p&gt;

&lt;p&gt;To do so, we dive into the HTML document using the document API and get that value with &lt;code&gt;count.innerText&lt;/code&gt;. The &lt;code&gt;innerText&lt;/code&gt; value is a string, so we convert it to a number, add 1, and then write that value back to &lt;code&gt;count.innerText&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To make the decrement button work, we do the same steps again. The only difference is that we use the expression &lt;code&gt;Number(count.innerText - 1)&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Counter App&amp;lt;/title&amp;gt;
    &amp;lt;meta charset="UTF-8" /&amp;gt;
  &amp;lt;/head&amp;gt;
   &amp;lt;body&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;button id="increment"&amp;gt;+ 1&amp;lt;/button&amp;gt;
      &amp;lt;span id="count"&amp;gt;0&amp;lt;/span&amp;gt;
      &amp;lt;button id="decrement"&amp;gt;- 1&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;

    &amp;lt;script&amp;gt;
      const increment = document.querySelector("#increment");
      const count = document.querySelector("#count");
      const decrement = document.querySelector("#decrement");

      increment.addEventListener("click", () =&amp;gt; {
        count.innerText = Number(count.innerText) + 1;
      });

      decrement.addEventListener("click", () =&amp;gt; {
        count.innerText = Number(count.innerText) - 1;
      });
    &amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This isn't too much code, but you can see that there are a number of steps here that are not very intuitive and repetitive:&lt;/p&gt;

&lt;p&gt;. Add arbitrary id to HTML elements&lt;br&gt;
. Query for the element using JavaScript&lt;br&gt;
. Store element reference in variable&lt;br&gt;
. Listen for appropriate event on element&lt;br&gt;
. Get current state value using &lt;code&gt;document API&lt;/code&gt;&lt;br&gt;
. Write new state value back to the page with .&lt;code&gt;innerText&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;These are a lot of low-level instructions that are required for our program to operate, but they don't help us thinking about the underlying state.&lt;/p&gt;

&lt;p&gt;As we saw, the state lives in the browser. This means we have to "find" the state first and then &lt;strong&gt;imperatively&lt;/strong&gt; (in a way that the computer understands better than we do) update that value.&lt;/p&gt;

&lt;p&gt;Fortunately, React gives us a much easier way of updating state and thinking about state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How does React help us manage state?&lt;/strong&gt;&lt;br&gt;
One significant benefit of using React and why it's in your interest to use React in develop your JavaScript applications is that it gives you much easier patterns for updating your state.&lt;/p&gt;

&lt;p&gt;Unlike plain JavaScript, React takes care of the difficult work of updating what the user sees. All we have to do is tell it what state we're managing and what the new value should be.&lt;/p&gt;

&lt;p&gt;Instead of the state living within the browser and having to find it every time we need to read it or update it, we are able to simply put it in a variable and then update that variable's value. After we do that, the update and new value will be displayed to our users.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This is the whole concept of managing state in React.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Instead of using an HTML document, we can write all of our markup within a React component.&lt;/p&gt;

&lt;p&gt;It is written identically to a regular JavaScript function and it displays the same HTML elements using an identical syntax called JSX.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function Counter() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button&amp;gt;+ 1&amp;lt;/button&amp;gt;
      &amp;lt;span&amp;gt;0&amp;lt;/span&amp;gt;
      &amp;lt;button&amp;gt;- 1&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How can we make the same counter application with React?&lt;/p&gt;

&lt;p&gt;In our React app, once we've identified what our state is, we control it using a JavaScript variable.&lt;/p&gt;

&lt;p&gt;This variable can be declared in many ways. The most popular way to manage component state is with the &lt;code&gt;useState&lt;/code&gt; hook.&lt;/p&gt;

&lt;p&gt;A hook in React works very similarly to regular JavaScript functions. That means we can call it up at the top of our component and we pass it the default value as the starting value for our counter app.&lt;/p&gt;

&lt;p&gt;Since the starting value of our count value is zero, we just call our hook and pass it the value &lt;code&gt;0&lt;/code&gt;and that value is put into our state variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';

export default function Counter() {
  // the count value lives and is managed up here!
  const [count] = useState(0);  

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button&amp;gt;+ 1&amp;lt;/button&amp;gt;
      &amp;lt;span&amp;gt;{count}&amp;lt;/span&amp;gt; {/* use curly braces to output the count value: 0 */}
      &amp;lt;button&amp;gt;- 1&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There's no need to use &lt;code&gt;count.innerText&lt;/code&gt; anymore. We can just output and read the value of our state by using &lt;code&gt;count&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Just like any JavaScript variable, we can name it however we want. It doesn't have to be called &lt;code&gt;count&lt;/code&gt;. You could call it literally anything else as long as its a valid JavaScript name.&lt;/p&gt;

&lt;p&gt;The return value from &lt;code&gt;useState&lt;/code&gt; is an array. When we destructure it, the first destructured value is the state variable. The second one is the function to update state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);  

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button&amp;gt;+ 1&amp;lt;/button&amp;gt;
      &amp;lt;span&amp;gt;{count}&amp;lt;/span&amp;gt;
      &amp;lt;button&amp;gt;- 1&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How do we make the increment button work?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here's what we don't need to do:&lt;/p&gt;

&lt;p&gt;1 We don't need to add an &lt;code&gt;id&lt;/code&gt; to our HTML elements&lt;br&gt;
2 We don't need to dive into the &lt;em&gt;DOM&lt;/em&gt; and figure out &lt;br&gt;
  which button is which&lt;br&gt;
3 We don't need to listen for a click event with&lt;br&gt;
  &lt;code&gt;document.addEventListener&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;To update state when you click on a button, add the&lt;code&gt;onClick&lt;/code&gt; prop to each button. This allows you to call a function when the button is pressed by the user.&lt;/p&gt;

&lt;p&gt;For the increment button, we will update state by passing &lt;code&gt;count + 1&lt;/code&gt; to &lt;code&gt;setCount&lt;/code&gt;, and for the decrement button, we will pass &lt;code&gt;count - 1&lt;/code&gt;to &lt;code&gt;setCount&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);  

  function incrementCount() {
    setCount(count + 1);
  }

  function decrementCount() {
    setCount(count - 1);   
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={incrementCount}&amp;gt;+ 1&amp;lt;/button&amp;gt;
      &amp;lt;span&amp;gt;{count}&amp;lt;/span&amp;gt;
      &amp;lt;button onClick={decrementCount}&amp;gt;- 1&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is all the code we need to create a working counter app with React.&lt;/p&gt;

&lt;p&gt;When each button is pressed and state is updated, React will do all the work of updating the page so that the user can see the new state.&lt;/p&gt;

&lt;p&gt;This is the great benefit of using React versus plain JavaScript: when state is managed using hooks like &lt;code&gt;useState&lt;/code&gt;and React takes care of efficiently updating what the user sees, we can create simpler, more reliable apps where state is easy to see.&lt;br&gt;
Thanks for reading,&lt;/p&gt;

</description>
    </item>
    <item>
      <title>The JavaScript Skills You Need For React</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Tue, 22 Mar 2022 02:23:11 +0000</pubDate>
      <link>https://dev.to/sananayab/the-javascript-skills-you-need-for-react-4can</link>
      <guid>https://dev.to/sananayab/the-javascript-skills-you-need-for-react-4can</guid>
      <description>&lt;p&gt;One of the most important things to understand about React is that it is fundamentally JavaScript. This means that the better you are at JavaScript, the more successful you will be with React.&lt;/p&gt;

&lt;p&gt;Let's break down the 7 essential concepts that you should know about JavaScript to master React.&lt;/p&gt;

&lt;p&gt;And when I say these concepts are essential, I mean that they are used in every single application that a React developer makes, with little to no exceptions.&lt;/p&gt;

&lt;p&gt;Learning these concepts is one of the most valuable things you can do to accelerate your ability to make React projects and become a skilled React developer, so let's get started.&lt;br&gt;
&lt;strong&gt;1. Function Declarations and Arrow Functions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The basis of any React application is the component. In React, components are defined with both JavaScript functions and classes.&lt;/p&gt;

&lt;p&gt;But unlike JavaScript functions, React components return JSX elements that are used to structure our application interface.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// JavaScript function: returns any valid JavaScript type
function javascriptFunction() {
  return "Hello world";
}

// React function component: returns JSX
function ReactComponent(props) {
  return &amp;lt;h1&amp;gt;{props.content}&amp;lt;/h1&amp;gt;   
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note the different casing between the names of JavaScript functions and React function components. JavaScript functions are named in camel casing, while React function components are written with pascal casing (in which all words are capitalized).&lt;/p&gt;

&lt;p&gt;There are two different ways to write a function in JavaScript: the traditional way, using the &lt;code&gt;function&lt;/code&gt; keyword, called a &lt;strong&gt;function declaration&lt;/strong&gt;, and as an &lt;strong&gt;arrow function&lt;/strong&gt;, which was introduced in ES6.&lt;/p&gt;

&lt;p&gt;Both function declarations and arrow functions can be used to write function components in React.&lt;/p&gt;

&lt;p&gt;The primary benefit of arrow functions is their succinctness. We can use several shorthands in order to write our functions to remove unnecessary boilerplate, such that we can even write it all on a single line.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Function declaration syntax
function MyComponent(props) {
  return &amp;lt;div&amp;gt;{props.content}&amp;lt;/div&amp;gt;;
}

// Arrow function syntax
const MyComponent = (props) =&amp;gt; {
  return &amp;lt;div&amp;gt;{props.content}&amp;lt;/div&amp;gt;;
} 
// Arrow function syntax (shorthand)
const MyComponent = props =&amp;gt; &amp;lt;div&amp;gt;{props.content}&amp;lt;/div&amp;gt;;

/* 
In the last example we are using several shorthands that arrow functions allow:

1. No parentheses around a single parameter
2. Implicit return (as compared to using the "return" keyword)
3. No curly braces for function body
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One small benefit of using function declarations over arrow functions is that you don't have to worry about problems with hoisting.&lt;/p&gt;

&lt;p&gt;Due to the JavaScript behavior of hoisting, you can use multiple function components made with function declarations in a single file in whichever order you like.&lt;/p&gt;

&lt;p&gt;Function components made with arrow functions, however, cannot be ordered whichever way you like. Because JavaScript variables are hoisted, arrow function components must be declared before they are used:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  return (
    &amp;lt;&amp;gt;
      {/* Valid! FunctionDeclaration is hoisted */}
      &amp;lt;FunctionDeclaration /&amp;gt;
      {/* Invalid! ArrowFunction is NOT hoisted. Therefore, it must be declared before it is used */}
      &amp;lt;ArrowFunction /&amp;gt;
    &amp;lt;/&amp;gt;
}

function FunctionDeclaration() {
  return &amp;lt;div&amp;gt;Hello React!&amp;lt;/div&amp;gt;;   
}

function ArrowFunction() {
  return &amp;lt;div&amp;gt;Hello React, again!&amp;lt;/div&amp;gt;;   
}  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another small difference in using the function declaration syntax is that you can immediately export a component from a file using &lt;code&gt;export default&lt;/code&gt; or &lt;code&gt;export&lt;/code&gt; before the function is declared. You can only use the &lt;code&gt;export&lt;/code&gt; keyword before arrow functions (default exports must be placed on a line below the component).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Function declaration syntax can be immediately exported with export default or export
export default function App() {
  return &amp;lt;div&amp;gt;Hello React&amp;lt;/div&amp;gt;;   
}

// Arrow function syntax must use export only
export const App = () =&amp;gt; {
  return &amp;lt;div&amp;gt;Hello React&amp;lt;/div&amp;gt;;     
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Template Literals&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;JavaScript has a clumsy history of working with strings, particularly if you want to concatenate or connect multiple strings together. Before the arrival of ES6, to add strings together you needed to use the&lt;code&gt;+&lt;/code&gt;operator to add each string segment to one another.&lt;/p&gt;

&lt;p&gt;With the addition of ES6, we were given a newer form of string called a template literal, which consists of two back ticks instead of single or double quotes.&lt;/p&gt;

&lt;p&gt;Instead of having to use the + operator, we can connect strings by putting a JavaScript expression (such as a variable) within a special &lt;code&gt;${}&lt;/code&gt; syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* 
Concatenating strings prior to ES6.
Notice the awkward space after the word Hello?
*/
function sayHello(text) {
  return 'Hello ' + text + '!';
}
sayHello('React'); // Hello React! 
/* 
Concatenating strings using template literals.
See how much more readable and predictable this code is?
*/
function sayHelloAgain(text) {
  return `Hello again, ${text}!`;
}

sayHelloAgain('React'); // Hello again, React!

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What's powerful about template literals is their ability to use any JavaScript expression (that is, anything in JavaScript that resolves to a value) within the &lt;code&gt;${}&lt;/code&gt; syntax.&lt;/p&gt;

&lt;p&gt;We can even include conditional logic using the ternary operator, which is perfect for conditionally adding or removing a class or style rule to a given JSX element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* Go to react.new and paste this code in to see it work! */
import React from "react";

function App() {
  const [isRedColor, setRedColor] = React.useState(false);

  const toggleColor = () =&amp;gt; setRedColor((prev) =&amp;gt; !prev);

  return (
    &amp;lt;button
      onClick={toggleColor}
      style={{
        background: isRedColor ? "red" : "black",
        color: 'white'
      }}
    &amp;gt;
      Button is {isRedColor ? "red" : "not red"}
    &amp;lt;/button&amp;gt;
  );
}
export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In short, template literals are great for React whenever we need to dynamically create strings. For example, when we use string values that can change in our head or body elements in our site:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import Head from './Head';

function Layout(props) {
  // Shows site name (i.e. Reed Barger) at end of page title
  const title = `${props.title} | Reed Barger`; 
  return (
     &amp;lt;&amp;gt;
       &amp;lt;Head&amp;gt;
         &amp;lt;title&amp;gt;{title}&amp;lt;/title&amp;gt;
       &amp;lt;/Head&amp;gt;
       &amp;lt;main&amp;gt;
        {props.children}
       &amp;lt;/main&amp;gt;
     &amp;lt;/&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Short Conditionals: &amp;amp;&amp;amp;, ||, Ternary Operator&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Considering that React is just JavaScript, it is very easy to conditionally show (or hide) JSX elements using simple if statements and sometimes switch statements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

function App() {
  const isLoggedIn = true;

  if (isLoggedIn) {
    // Shows: Welcome back!
    return &amp;lt;div&amp;gt;Welcome back!&amp;lt;/div&amp;gt;;
  }

  return &amp;lt;div&amp;gt;Who are you?&amp;lt;/div&amp;gt;;
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the help of some essential JavaScript operators, we cut down on repetition and make our code more concise.&lt;/p&gt;

&lt;p&gt;We can transform the if statement above into the following, using the ternary operator. The ternary operator functions exactly the same as an if-statement, but it is shorter, it is an expression (not a statement), and can be inserted within JSX:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

function App() {
  const isLoggedIn = true;

  // Shows: Welcome back!
  return isLoggedIn ? &amp;lt;div&amp;gt;Welcome back!&amp;lt;/div&amp;gt; : &amp;lt;div&amp;gt;Who are you?&amp;lt;/div&amp;gt;
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ternary operators can also be used inside curly braces (again, since it is an expression):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

function App() {
  const isLoggedIn = true;

  // Shows: Welcome back!
  return &amp;lt;div&amp;gt;{isLoggedIn ? "Welcome back!" : "Who are you?"&amp;lt;/div&amp;gt;;
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we were to change the example above and only wanted to show text if the user was logged in (if &lt;code&gt;isLoggedIn&lt;/code&gt; is true), this would be a great use case for the &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; (and) operator.&lt;/p&gt;

&lt;p&gt;If the first value (operand) in the conditional is true, the &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt;operator displays the second operand. Otherwise it returns the first operand. And since it is falsy (is a value automatically converted to the boolean &lt;code&gt;false&lt;/code&gt; by JavaScript), it is not rendered by JSX:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

function App() {
  const isLoggedIn = true;

  // If true: Welcome back!, if false: nothing
  return &amp;lt;div&amp;gt;{isLoggedIn &amp;amp;&amp;amp; "Welcome back!"}&amp;lt;/div&amp;gt;;
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's say that we want the reverse of what we're doing now: to only say "Who are you?" if &lt;code&gt;isLoggedIn&lt;/code&gt; is false. If it's true, we won't show anything.&lt;/p&gt;

&lt;p&gt;For this logic, we can use the &lt;code&gt;||&lt;/code&gt; (or) operator. It essentially works opposite to the &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt;operator. If the first operand is true, the first (falsy) operand is returned. If the first operand is false, the second operand is returned.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

function App() {
  const isLoggedIn = true;

  // If true: nothing, if false: Who are you?
  return &amp;lt;div&amp;gt;{isLoggedIn || "Who are you?"}&amp;lt;/div&amp;gt;;
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Three Array Methods: .map(), .filter(), .reduce()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Inserting primitive values into JSX elements is easy – just use curly braces.&lt;/p&gt;

&lt;p&gt;We can insert any valid expressions, including variables that contain primitive values (strings, numbers, booleans, and so on) as well as object properties that contain primitive values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

function App() {
  const name = "Reed";
  const bio = {
    age: 28,
    isEnglishSpeaker: true
  };

  return (
    &amp;lt;&amp;gt;
      &amp;lt;h1&amp;gt;{name}&amp;lt;/h1&amp;gt;
      &amp;lt;h2&amp;gt;I am {bio.age} years old&amp;lt;/h2&amp;gt;
      &amp;lt;p&amp;gt;Speaks English: {bio.isEnglishSpeaker}&amp;lt;/p&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What if we have an array and we want to iterate over that array to show each array element within an individual JSX element?&lt;/p&gt;

&lt;p&gt;For this, we can use the &lt;code&gt;.map()&lt;/code&gt; method. It allows us to transform each element in our array in the way we specify with the inner function.&lt;/p&gt;

&lt;p&gt;Note that it is especially concise when used in combination with an arrow function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* Note that this isn't exactly the same as the normal JavaScript .map() method, but is very similar. */
import React from "react";

function App() {
  const programmers = ["Reed", "John", "Jane"];

  return (
    &amp;lt;ul&amp;gt;
      {programmers.map(programmer =&amp;gt; &amp;lt;li&amp;gt;{programmer}&amp;lt;/li&amp;gt;)}
    &amp;lt;/ul&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are other flavors of the .map() method that perform related tasks and are important to know because they can be chained in combination with one another.&lt;/p&gt;

&lt;p&gt;Why? Because &lt;code&gt;.map()&lt;/code&gt;, like many array methods, returns a shallow copy of the array that it has iterated over. This enables its returned array to be passed onto the next method in the chain.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.filter()&lt;/code&gt;, as its name indicates, allows us to filter certain elements out of our array. For example, if we wanted to remove all names of programmers that started with "J", we could do so with &lt;code&gt;.filter()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
function App() {
  const programmers = ["Reed", "John", "Jane"];

  return (
    &amp;lt;ul&amp;gt;
      {/* Returns 'Reed' */}
      {programmers
       .filter(programmer =&amp;gt; !programmer.startsWith("J"))
       .map(programmer =&amp;gt; &amp;lt;li&amp;gt;{programmer}&amp;lt;/li&amp;gt;)}
    &amp;lt;/ul&amp;gt;
  );
}
export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's important to understand that both &lt;code&gt;.map()&lt;/code&gt;and&lt;code&gt;.filter()&lt;/code&gt; are just different variations of the &lt;code&gt;.reduce()&lt;/code&gt;array method, which is capable of transforming array values into virtually any data type, even non-array values.&lt;/p&gt;

&lt;p&gt;Here's &lt;code&gt;.reduce()&lt;/code&gt; performing the same operation as our &lt;code&gt;.filter()&lt;/code&gt; method above:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

function App() {
  const programmers = ["Reed", "John", "Jane"];

  return (
    &amp;lt;ul&amp;gt;
      {/* Returns 'Reed' */}
      {programmers
        .reduce((acc, programmer) =&amp;gt; {
          if (!programmer.startsWith("J")) {
            return acc.concat(programmer);
          } else {
            return acc;
          }
        }, [])
        .map((programmer) =&amp;gt; (
          &amp;lt;li&amp;gt;{programmer}&amp;lt;/li&amp;gt;
        ))}
    &amp;lt;/ul&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Object Tricks: Property Shorthand, Destructuring, Spread Operator&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Like arrays, objects are a data structure that you need to be comfortable with when using React.&lt;/p&gt;

&lt;p&gt;Since objects exist for the sake of organized key-value storage, unlike arrays, you're going to need to be very comfortable accessing and manipulating object properties.&lt;/p&gt;

&lt;p&gt;To add properties to an object as you create it, you name the property and its corresponding value. One very simple shorthand to remember is that if the property name is the same as the value, you only have to list the property name.&lt;/p&gt;

&lt;p&gt;This is the object property shorthand:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const name = "Reed";

const user = {
  // instead of name: name, we can use...
  name
};

console.log(user.name); // Reed

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The standard way to access properties from an object is using the dot notation. An even more convenient approach, however, is object destructuring. It allows us to extract properties as individual variables of the same name from a given object.&lt;/p&gt;

&lt;p&gt;It looks somewhat like you're writing an object in reverse, which is what makes the process intuitive. It's much nicer to use than having to use the object name multiple times to access each time you want to grab a value from it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const user = {
  name: "Reed",
  age: 28,
  isEnglishSpeaker: true
};
// Dot property access
const name = user.name;
const age = user.age;
// Object destructuring
const { age, name, isEnglishSpeaker: knowsEnglish } = user;
// Use ':' to rename a value as you destructure it
console.log(knowsEnglish); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if you want to create objects from existing ones, you could list properties one-by-one, but that can get very repetitive.&lt;/p&gt;

&lt;p&gt;Instead of copying properties manually, you can spread all of an object's properties into another object (as you create it) using the object spread operator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const user = {
  name: "Reed",
  age: 28,
  isEnglishSpeaker: true
};

const firstUser = {
  name: user.name,
  age: user.age,
  isEnglishSpeaker: user.isEnglishSpeaker
};

// Copy all of user's properties into secondUser 
const secondUser = {
  ...user  
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What is great about the object spread is that you can spread in as many objects into a new one as you like, and you can order them like properties. But be aware that properties that come later with the same name will overwrite previous properties:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const user = {
  name: "Reed",
  age: 28
};
const moreUserInfo = {
  age: 70,
  country: "USA"
};

// Copy all of user's properties into secondUser 
const secondUser = {
  ...user,
  ...moreUserInfo,
   computer: "MacBook Pro"
};

console.log(secondUser);
// { name: "Reed", age: 70, country: "USA", computer: "Macbook Pro" }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6: Promises + Async/Await Syntax&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Virtually every React application consists of &lt;strong&gt;asynchronous code&lt;/strong&gt; – code that takes an indefinite amount of time to be executed. Particularly if you need to get or change data from an external API using browser features like the &lt;strong&gt;Fetch API&lt;/strong&gt; or the third-party library &lt;strong&gt;axios&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Promises are used to resolve asynchronous code to make it resolve like normal, synchronous code, which we can read from top to bottom.&lt;/p&gt;

&lt;p&gt;Promises traditionally use callbacks to resolve our asynchronous code. We use the &lt;code&gt;.then()&lt;/code&gt; callback to resolve successfully resolved promises, while we use the &lt;code&gt;.catch()&lt;/code&gt; callback to resolve promises that respond with an error.&lt;/p&gt;

&lt;p&gt;Here is a real example of using React to fetch data from my &lt;strong&gt;GitHub API&lt;/strong&gt; using the &lt;strong&gt;Fetch API&lt;/strong&gt; to show my profile image. The data is resolved using promises:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* Go to react.new and paste this code in to see it work! */
import React from 'react';

const App = () =&amp;gt; {
  const [avatar, setAvatar] = React.useState('');

  React.useEffect(() =&amp;gt; {
    /* 
      The first .then() lets us get JSON data from the response.
      The second .then() gets the url to my avatar and puts it in state. 
    */
    fetch('https://api.github.com/users/reedbarger')
      .then(response =&amp;gt; response.json())
      .then(data =&amp;gt; setAvatar(data.avatar_url))
      .catch(error =&amp;gt; console.error("Error fetching data: ", error);
  }, []);

  return (
    &amp;lt;img src={avatar} alt="Reed Barger" /&amp;gt;
  );
};

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of always needing to use callbacks to resolve our data from a promise, we can use a cleaned syntax that looks identical to synchronous code, called the &lt;strong&gt;async/await syntax&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The async and await keywords are only used with functions (normal JavaScript functions, not React function components).&lt;/p&gt;

&lt;p&gt;To use them, we need to make sure our asynchronous code is in a function prepended with the keyword &lt;code&gt;async&lt;/code&gt;. Any promise's value can then be resolved by placing the keyword &lt;code&gt;await&lt;/code&gt; before it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* Go to react.new and paste this code in to see it work! */
import React from "react";

const App = () =&amp;gt; {
  const [avatar, setAvatar] = React.useState("");

  React.useEffect(() =&amp;gt; {
    /* 
      Note that because the function passed to useEffect cannot be async, we must create a separate function for our promise to be resolved in (fetchAvatar)
    */
    async function fetchAvatar() {
      const response = await fetch("https://api.github.com/users/reedbarger");
      const data = await response.json();
      setAvatar(data.avatar_url);
    }

    fetchAvatar();
  }, []);

  return &amp;lt;img src={avatar} alt="Reed Barger" /&amp;gt;;
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We use the &lt;code&gt;.catch()&lt;/code&gt; callback to handle errors within traditional promises, but how do you catch errors with async/await?&lt;/p&gt;

&lt;p&gt;We still use &lt;code&gt;.catch()&lt;/code&gt; and when we hit an error, such as when we have a response from our API that is in the 200 or 300 status range:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* Go to react.new and paste this code in to see it work! */
import React from "react";

const App = () =&amp;gt; {
  const [avatar, setAvatar] = React.useState("");

  React.useEffect(() =&amp;gt; {
    async function fetchAvatar() {
      /* Using an invalid user to create a 404 (not found) error */
      const response = await fetch("https://api.github.com/users/reedbarge");
      if (!response.ok) {
        const message = `An error has occured: ${response.status}`;
        /* In development, you'll see this error message displayed on your screen */
        throw new Error(message);
      }
      const data = await response.json();

      setAvatar(data.avatar_url);
    }

    fetchAvatar();
  }, []);

  return &amp;lt;img src={avatar} alt="Reed Barger" /&amp;gt;;
};
export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;7. ES Modules + Import / Export syntax&lt;/strong&gt;&lt;br&gt;
ES6 gave us the ability to easily share code between our own JavaScript files as well as third-party libraries using ES modules.&lt;/p&gt;

&lt;p&gt;Also, when we leverage tools like Webpack, we can import assets like images and svgs, as well as CSS files and use them as dynamic values in our code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* We're bringing into our file a library (React), a png image, and CSS styles */
import React from 'react';
import logo from '../img/site-logo.png';
import '../styles/app.css';

function App() {
  return (
    &amp;lt;div&amp;gt;
      Welcome!
      &amp;lt;img src={logo} alt="Site logo" /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The idea behind ES modules is to be able to split up our JavaScript code into different files, to make it modular or reusable across our app.&lt;/p&gt;

&lt;p&gt;As far as JavaScript code goes, we can import and export variables and functions. There are two ways of importing and exporting, as &lt;strong&gt;named&lt;/strong&gt; &lt;strong&gt;imports/exports **and as default **imports/exports&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;There can only be one thing we make a default import or export per file and we can make as many things named imports/export as we like. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// constants.js
export const name = "Reed";

export const age = 28;

export default function getName() {
  return name;   
}
// app.js
// Notice that named exports are imported between curly braces
import getName, { name, age } from '../constants.js';
console.log(name, age, getName());

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also write all of the exports at the end of the file instead of next to each variable or function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// constants.js
const name = "Reed";

const age = 28;

function getName() {
  return name;   
}

export { name, age };
export default getName;

// app.js
import getName, { name, age } from '../constants.js';

console.log(name, age, getName());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also alias or rename what you are importing using the as keyword for named imports. The benefit of default exports is that they can be named to whatever you like.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// constants.js
const name = "Reed";

const age = 28;

function getName() {
  return name;   
}

export { name, age };
export default getName;

// app.js
import getMyName, { name as myName, age as myAge } from '../constants.js';

console.log(myName, myAge, getMyName());

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
    </item>
    <item>
      <title>React Context for Beginners</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Fri, 18 Mar 2022 18:14:45 +0000</pubDate>
      <link>https://dev.to/sananayab/react-context-for-beginners-1egf</link>
      <guid>https://dev.to/sananayab/react-context-for-beginners-1egf</guid>
      <description>&lt;p&gt;&lt;strong&gt;React context&lt;/strong&gt; is an essential tool for every React developer to know. where we  easily share state in our applications.&lt;/p&gt;

&lt;p&gt;In this comprehensive guide, I will cover what React context is, how to use it, when and when not to use context, and lots more.&lt;/p&gt;

&lt;p&gt;Here You will know everything you need to know with simple, step-by-step examples.&lt;/p&gt;

&lt;p&gt;Let's get started!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is React context?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React context allows us to pass down and use (consume) data in whatever component we need in our React app without using  props.&lt;/p&gt;

&lt;p&gt;In other words, React context allows us to share data (state) across our components more easily.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When should we use React context?&lt;/strong&gt;&lt;br&gt;
React context is great when we are passing data that can be used in any component in our application.&lt;/p&gt;

&lt;p&gt;These types of data include:&lt;/p&gt;

&lt;p&gt;Theme data (like dark or light mode)&lt;/p&gt;

&lt;p&gt;User data (the currently authenticated user)&lt;br&gt;
Location-specific data (like user language or locale)&lt;br&gt;
Data should be placed on React context that does not need to be updated often.&lt;/p&gt;

&lt;p&gt;Why? Because context was not made as an entire state management system. It was made to make consuming data easier.&lt;/p&gt;

&lt;p&gt;You can think of React context as the equivalent of global variables for our React components.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What problems does React context solve?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React context helps us avoid the problem of props drilling.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Props drilling&lt;/code&gt; is a term to describe when we pass props down multiple levels to a nested component, through components that don't need it.&lt;/p&gt;

&lt;p&gt;Here is an example of props drilling. In this application, we have access to theme data that we want to pass as a prop to all of our app's components.&lt;/p&gt;

&lt;p&gt;As you can see, however, the direct children of &lt;code&gt;App&lt;/code&gt;, such as &lt;code&gt;Header&lt;/code&gt;, also have to pass the theme data down using props.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function App({ theme }) {
  return (
    &amp;lt;&amp;gt;
      &amp;lt;Header theme={theme} /&amp;gt;
      &amp;lt;Main theme={theme} /&amp;gt;
      &amp;lt;Sidebar theme={theme} /&amp;gt;
      &amp;lt;Footer theme={theme} /&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

function Header({ theme }) {
  return (
    &amp;lt;&amp;gt;
      &amp;lt;User theme={theme} /&amp;gt;
      &amp;lt;Login theme={theme} /&amp;gt;
      &amp;lt;Menu theme={theme} /&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;What is the issue with this example?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The issue is that we are drilling the &lt;code&gt;theme&lt;/code&gt; prop through multiple components that don't immediately need it.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Header&lt;/code&gt; component doesn't need &lt;code&gt;theme&lt;/code&gt; other than to pass it down to its child component. In other words, it would be better for &lt;code&gt;User&lt;/code&gt; , Login &lt;code&gt;and Menu to consume the&lt;/code&gt;theme` data directly.&lt;/p&gt;

&lt;p&gt;This is the benefit of React context – we can bypass using props entirely and therefore avoid the issue of props drilling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do I use React context?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Context is an API that is built into React, starting from React version 16.&lt;/p&gt;

&lt;p&gt;This means that we can create and use context directly by importing React in any React project.&lt;/p&gt;

&lt;p&gt;There are four steps to using React context:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Create context using the &lt;code&gt;createContext&lt;/code&gt; method.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Take your created context and wrap the context provider         around your component tree.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Put any value you like on your context provider using the value prop.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Read that value within any component by using the context consumer.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Does all this sound confusing? It's simpler than you think.&lt;/p&gt;

&lt;p&gt;Let's take a look at a very basic example. In our &lt;code&gt;App&lt;/code&gt;, let's pass down our own name using &lt;code&gt;Context &lt;/code&gt;and read it in a nested component: &lt;code&gt;User&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;br&gt;
import React from 'react';&lt;/p&gt;

&lt;p&gt;export const UserContext = React.createContext();&lt;/p&gt;

&lt;p&gt;export default function App() {&lt;br&gt;
  return (&lt;br&gt;
    &lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
  )&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function User() {&lt;br&gt;
  return (&lt;br&gt;
    &lt;br&gt;
      {value =&amp;gt; &lt;/p&gt;
&lt;h1&gt;{value}&lt;/h1&gt;} &lt;br&gt;
      {/* prints: Reed */}&lt;br&gt;
    &lt;br&gt;
  )&lt;br&gt;
}&lt;br&gt;
`&lt;code&gt;&lt;/code&gt;

&lt;p&gt;&lt;strong&gt;Let's break down what we are doing, step-by-step:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Above our &lt;code&gt;App &lt;/code&gt;component, we are creating context with &lt;code&gt;React.createContext()&lt;/code&gt; and putting the result in a variable, &lt;code&gt;UserContext&lt;/code&gt;. In almost every case, you will want to export it as we are doing here because your component will be in another file. Note that we can pass an initial &lt;code&gt;value&lt;/code&gt; to our value prop when we call &lt;code&gt;React.createContext()&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In our &lt;code&gt;App&lt;/code&gt; component, we are using &lt;code&gt;UserContext&lt;/code&gt;.  Specifically &lt;code&gt;UserContext.Provider&lt;/code&gt;. The created context is an object with two properties: &lt;code&gt;Provider&lt;/code&gt; and &lt;code&gt;Consumer&lt;/code&gt;, both of which are components. To pass our value down to every component in our App, we wrap our Provider component around it (in this case, &lt;code&gt;User&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;On &lt;code&gt;UserContext.Provider&lt;/code&gt;, we put the value that we want to pass down our entire component tree. We set that equal to the &lt;code&gt;value&lt;/code&gt; prop to do so. In this case, it is our name (here, Reed).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In &lt;code&gt;User&lt;/code&gt;, or wherever we want to consume (or use) what was provided on our context, we use the consumer component: &lt;code&gt;UserContext.Consumer&lt;/code&gt;. To use our passed down value, we use what is called the render props pattern. It is just a function that the consumer component gives us as a prop. And in the return of that function, we can return and use &lt;code&gt;value&lt;/code&gt;.&lt;br&gt;
&lt;strong&gt;What is the useContext hook?&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Looking at the example above, the render props pattern for consuming context may look a bit strange to you.&lt;/p&gt;

&lt;p&gt;Another way of consuming context became available in React 16.8 with the arrival of React hooks. We can now consume context with the &lt;strong&gt;useContext hook&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Instead of using render props, we can pass the entire context object to&lt;code&gt; React.useContext()&lt;/code&gt; to consume context at the top of our component.&lt;/p&gt;

&lt;p&gt;Here is the example above using the useContext hook:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;&lt;br&gt;
&lt;/code&gt;import React from 'react';&lt;br&gt;
export const UserContext = React.createContext();&lt;br&gt;
export default function App() {&lt;br&gt;
  return (&lt;br&gt;
    &lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
  )&lt;br&gt;
}&lt;br&gt;
function User() {&lt;br&gt;
const value = React.useContext(UserContext);  &lt;/p&gt;

&lt;p&gt;return &lt;/p&gt;
&lt;h1&gt;{value}&lt;/h1&gt;;&lt;br&gt;
}&lt;br&gt;
&lt;code&gt;&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;

&lt;p&gt;The benefit of the useContext hook is that it makes our components more concise and allows us to create our own custom hooks.&lt;/p&gt;

&lt;p&gt;You can either use the consumer component directly or the useContext hook, depending on which pattern you prefer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;You may not need context&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The mistake many developers make is reaching for context when once they have to pass props down several levels to a component.&lt;/p&gt;

&lt;p&gt;Here is an application with a nested &lt;code&gt;Avatar&lt;/code&gt; component that requires two props &lt;code&gt;username&lt;/code&gt; and &lt;code&gt;avatarSrc&lt;/code&gt; from the &lt;code&gt;App&lt;/code&gt; component.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;&lt;br&gt;
&lt;/code&gt;export default function App({ user }) {&lt;br&gt;
  const { username, avatarSrc } = user;&lt;br&gt;
   return (&lt;br&gt;
    &lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}&lt;br&gt;
function Navbar({ username, avatarSrc }) {&lt;br&gt;
  return (&lt;br&gt;
    &lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function Avatar({ username, avatarSrc }) {&lt;br&gt;
  return &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ox01XGpm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/%7BavatarSrc%7D" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ox01XGpm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/%7BavatarSrc%7D" alt="{username}" width="" height=""&gt;&lt;/a&gt;;&lt;br&gt;
}&lt;br&gt;
&lt;code&gt;&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;br&gt;
If possible, we want to avoid passing multiple props through components that don't need it.&lt;/p&gt;

&lt;p&gt;What can we do?&lt;/p&gt;

&lt;p&gt;Instead of immediately resorting to context because we are prop drilling, we should better compose our components.&lt;/p&gt;

&lt;p&gt;Since only the top most component, &lt;code&gt;App&lt;/code&gt;, needs to know about the &lt;code&gt;Avatar&lt;/code&gt; component, we can create it directly within &lt;code&gt;App&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This allows us to pass down a single prop, avatar, instead of two.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;&lt;br&gt;
&lt;/code&gt;export default function App({ user }) {&lt;br&gt;
  const { username, avatarSrc } = user;&lt;br&gt;
  const avatar = &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ox01XGpm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/%7BavatarSrc%7D" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ox01XGpm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/%7BavatarSrc%7D" alt="{username}" width="" height=""&gt;&lt;/a&gt;;&lt;br&gt;
  return (&lt;br&gt;
    &lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function Navbar({ avatar }) {&lt;br&gt;
return {avatar};&lt;br&gt;
}&lt;br&gt;
&lt;code&gt;&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;br&gt;
In short: don't reach for context right away. See if you can better organize your components to avoid prop drilling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Does React context replace Redux?&lt;/strong&gt;&lt;br&gt;
Yes and no.&lt;/p&gt;

&lt;p&gt;For many React beginners, Redux is a way of more easily passing around data. This is because Redux comes with React context itself.&lt;/p&gt;

&lt;p&gt;However, if you are not also updating state, but merely passing it down your component tree, you do not need a global state management library like Redux.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;React context caveats&lt;/strong&gt;&lt;br&gt;
Why it is not possible to update the value that React context passes down?&lt;/p&gt;

&lt;p&gt;While it is possible to combine React context with a hook like useReducer and create a makeshift state management library without any third-party library, it is generally not recommended for performance reasons.&lt;/p&gt;

&lt;p&gt;The issue with this approach lies in the way that React context triggers a re-render.&lt;/p&gt;

&lt;p&gt;If we are passing down an object on our React context provider and any property on it updates, what happens? Any component which consumes that context will re-render.&lt;/p&gt;

&lt;p&gt;This may not be a performance issue in smaller apps with few state values that are not updated very often (such as theme data). But it is a problem if you will be performing many state updates in an application with a lot of components in your component tree.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>reactcontex</category>
      <category>reactnative</category>
    </item>
    <item>
      <title>JavaScript Basics Before You Learn React</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Wed, 16 Mar 2022 08:32:06 +0000</pubDate>
      <link>https://dev.to/sananayab/javascript-basics-before-you-learn-react-4c6m</link>
      <guid>https://dev.to/sananayab/javascript-basics-before-you-learn-react-4c6m</guid>
      <description>&lt;p&gt;In an ideal world, you can learn all about JavaScript and web development before you dive into React. Unfortunately, we live in a not-perfect world, so chomping down on ALL of JavaScript before React will just make you bleed hard. If you already have some experience with JavaScript, all you need to learn before React is just the JavaScript features you will actually use to develop React application. Things about JavaScript you should be comfortable with before learning React are:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ES6 classes&lt;br&gt;
The new variable declaration let/const&lt;br&gt;
Arrow functions&lt;br&gt;
Destructuring assignment&lt;br&gt;
Map and filter&lt;br&gt;
ES6 module system&lt;/strong&gt;&lt;br&gt;
It's the 20% of JavaScript features that you will use 80% of the time, so in this tutorial I will help you learn them all.&lt;/p&gt;

&lt;p&gt;Exploring Create React App&lt;br&gt;
The usual case of starting to learn React is to run the create-react-app package, which sets up everything you need to run React. Then after the process is finished, opening src/app.js will present us with the only React class in the whole app:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      &amp;lt;div className="App"&amp;gt;
        &amp;lt;header className="App-header"&amp;gt;
          &amp;lt;img src={logo} className="App-logo" alt="logo" /&amp;gt;
          &amp;lt;p&amp;gt;
            Edit &amp;lt;code&amp;gt;src/App.js&amp;lt;/code&amp;gt; and save to reload.
          &amp;lt;/p&amp;gt;
          &amp;lt;a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          &amp;gt;
            Learn React
          &amp;lt;/a&amp;gt;
        &amp;lt;/header&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you never learned ES6 before, you'd think that this class statement is a feature of React. It's actually a new feature of ES6, and that's why learning ES6 properly would enable you to understand React code better. We'll start with ES6 classes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ES6 Classes&lt;/strong&gt;&lt;br&gt;
ES6 introduced class syntax that is used in similar ways to OO language like Java or Python. A basic class in ES6 would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Developer {
  constructor(name){
    this.name = name;
  }

  hello(){
    return 'Hello World! I am ' + this.name + ' and I am a web developer';
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;class syntax is followed by an identifier (or simply name) that can be used to create new objects. The constructor method is always called in object initialization. Any parameters passed into the object will be passed into the new object. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var sana = new Developer('sana');
sana.hello(); // Hello World! I am sana and I am a web developer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A class can define as many methods as the requirements needed, and in this case, we have the hello method which returns a string.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Class inheritance&lt;/strong&gt;&lt;br&gt;
A class can extends the definition of another class, and a new object initialized from that class will have all the methods of both classes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ReactDeveloper extends Developer {
  installReact(){
    return 'installing React .. Done.';
  }
}

var sana = new ReactDeveloper('sana');
sana.hello(); // Hello World! I am sanaand I am a web developer
sana.installReact(); // installing React .. Done.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The class that extends another class is usually called child class or sub class, and the class that is being extended is called parent class or super class. A child class can also override the methods defined in parent class, meaning it will replace the method definition with the new method defined. For example, let's override the hello function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ReactDeveloper extends Developer {
  installReact(){
    return 'installing React .. Done.';
  }

  hello(){
    return 'Hello World! I am ' + this.name + ' and I am a REACT developer';
  }
}

var sana = new ReactDeveloper('sana');
sana.hello(); // Hello World! I am sana and I am a REACT developer

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There you go. The hello method from Developer class has been overridden.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use in React&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that we understand ES6 class and inheritance, we can understand the React class defined in src/app.js. This is a React component, but it's actually just a normal ES6 class which inherits the definition of React Component class, which is imported from the React package.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from 'react';

class App extends Component {
  // class content
  render(){
    return (
      &amp;lt;h1&amp;gt;Hello React!&amp;lt;/h1&amp;gt;
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is what enables us to use the render() method, JSX, this.state, other methods. All of this definitions are inside the Component class. But as we will see later, class is not the only way to define React Component. If you don't need state and other lifecycle methods, you can use a function instead.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Declaring variables with ES6 let and const&lt;/strong&gt;&lt;br&gt;
Because JavaScript var keyword declares variable globally, two new variable declarations were introduced in ES6 to solve the issue, namely let and const. They are all the same, in which they are used to declare variables. The difference is that const cannot change its value after declaration, while let can. Both declarations are local, meaning if you declare let inside a function scope, you can't call it outside of the function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const name = "sana";
let age = 28;
var occupation = "Software Engineer";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Which one to use?&lt;/strong&gt;&lt;br&gt;
The rule of thumb is that declare variable using const by default. Later when you wrote the application, you'll realize that the value of const need to change. That's the time you should refactor const into let. Hopefully it will make you get used to the new keywords, and you'll start to recognize the pattern in your application where you need to use const or let.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When do we use it in React?&lt;/strong&gt;&lt;br&gt;
Everytime we need variables. Consider the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from 'react';

class App extends Component {
  // class content
  render(){
    const greeting = 'Welcome to React';
    return (
      &amp;lt;h1&amp;gt;{greeting}&amp;lt;/h1&amp;gt;
    )
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since greeting won't change in the entire application lifecycle, we define it using const here.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The arrow function&lt;/strong&gt;&lt;br&gt;
Arrow function is a new ES6 feature that's been used almost widely in modern codebases because it keeps the code concise and readable. This feature allows us to write functions using shorter syntax&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// regular function
const testFunction = function() {
  // content..
}

// arrow function
const testFunction = () =&amp;gt; {
  // content..
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you're an experienced JS developer, moving from the regular function syntax to arrow syntax might be uncomfortable at first. When I was learning about arrow function, &lt;/p&gt;

&lt;p&gt;I used this simple &lt;br&gt;
2 steps to rewrite my functions:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;remove function keyword&lt;/strong&gt;&lt;br&gt;
add the fat arrow symbol =&amp;gt; after ()&lt;br&gt;
the parentheses are still used for passing parameters, and if you only have one parameter, you can omit the parentheses.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const testFunction = (firstName, lastName) =&amp;gt; {
  return firstName+' '+lastName;
}

const singleParam = firstName =&amp;gt; {
  return firstName;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Implicit return&lt;/strong&gt;&lt;br&gt;
If your arrow function is only one line, you can return values without having to use the return keyword and the curly brackets {}&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const testFunction = () =&amp;gt; 'hello there.';
testFunction(); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Use in React&lt;/strong&gt;&lt;br&gt;
Another way to create React component is to use arrow function. React take arrow function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const HelloWorld = (props) =&amp;gt; {
  return &amp;lt;h1&amp;gt;{props.hello}&amp;lt;/h1&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;as equivalent to an ES6 class component&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class HelloWorld extends Component {
  render() {
    return (
      &amp;lt;h1&amp;gt;{props.hello}&amp;lt;/h1&amp;gt;;
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using arrow function in your React application makes the code more concise. But it will also remove the use of state from your component. This type of component is known as stateless functional component. You'll find that name in many React tutorials.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Destructuring assignment for arrays and objects&lt;/strong&gt;&lt;br&gt;
One of the most useful new syntax introduced in ES6, destructuring assignment is simply copying a part of object or array and put them into named variables. A quick example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const developer = {
  firstName: 'sana',
  lastName: 'Nayab',
  developer: true,
  age: 29,
}

//destructure developer object
const { firstName, lastName } = developer;
console.log(firstName); // returns 'Nathan'
console.log(lastName); // returns 'Sebhastian'
console.log(developer); // returns the object

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we assigned firstName and lastName from &lt;code&gt;developer&lt;/code&gt; object into new variable &lt;code&gt;firstName&lt;/code&gt; and &lt;code&gt;lastName&lt;/code&gt;. Now what if you want to put &lt;/p&gt;

&lt;p&gt;into a new variable called &lt;code&gt;name&lt;/code&gt;?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { firstName:name } = developer;
console.log(name); // returns 'sana'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Destructuring also works on arrays, only it uses index instead of object keys:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1,2,3,4,5];
const [one, two] = numbers; // one = 1, two = 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can skip some index from destructuring by passing it with &lt;code&gt;,&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [one, two, , four] = numbers; // one = 1, two = 2, four = 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Use in React&lt;/strong&gt;&lt;br&gt;
Mostly used in destructuring &lt;code&gt;state&lt;/code&gt; in methods, for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;reactFunction = () =&amp;gt; {
  const { name, email } = this.state;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or in functional stateless component, consider the example from previous chapter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const HelloWorld = (props) =&amp;gt; {
  return &amp;lt;h1&amp;gt;{props.hello}&amp;lt;/h1&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can simply destructure the parameter immediately:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const HelloWorld = ({ hello }) =&amp;gt; {
  return &amp;lt;h1&amp;gt;{hello}&amp;lt;/h1&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Destructuring array is also used on React's useState hook:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [user, setUser] = useState('');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Map and filter&lt;/strong&gt;&lt;br&gt;
Although this tutorial focuses on ES6, JavaScript array&lt;code&gt;map&lt;/code&gt;and &lt;code&gt;filter&lt;/code&gt; methods need to be mentioned since they are probably one of the most used ES5 features when building React application. Particularly on processing data.&lt;/p&gt;

&lt;p&gt;These two methods are much more used in processing data. For example, imagine a fetch from API result returns an array of JSON data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const users = [
  { name: 'Sana', age: 25 },
  { name: 'Hina', age: 30 },
  { name: 'Saba', age: 28 },
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we can render a list of items in React as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from 'react';

class App extends Component {
  // class content
  render(){
    const users = [
      { name: 'Sana', age: 25 },
      { name: 'Hina', age: 30 },
      { name: 'Saba', age: 28 },
    ];

    return (
      &amp;lt;ul&amp;gt;
        {users
          .map(user =&amp;gt; &amp;lt;li&amp;gt;{user.name}&amp;lt;/li&amp;gt;)
        }
      &amp;lt;/ul&amp;gt;
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also filter the data in the render.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ul&amp;gt;
  {users
    .filter(user =&amp;gt; user.age &amp;gt; 26)
    .map(user =&amp;gt; &amp;lt;li&amp;gt;{user.name}&amp;lt;/li&amp;gt;)
  }
&amp;lt;/ul&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;ES6 module system&lt;/strong&gt;&lt;br&gt;
The ES6 module system enables JavaScript to import and export files. Let's see the src/app.js code again in order to explain this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      &amp;lt;div className="App"&amp;gt;
        &amp;lt;header className="App-header"&amp;gt;
          &amp;lt;img src={logo} className="App-logo" alt="logo" /&amp;gt;
          &amp;lt;p&amp;gt;
            Edit &amp;lt;code&amp;gt;src/App.js&amp;lt;/code&amp;gt; and save to reload.
          &amp;lt;/p&amp;gt;
          &amp;lt;a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          &amp;gt;
            Learn React
          &amp;lt;/a&amp;gt;
        &amp;lt;/header&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Up at the first line of code we see the import statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from 'react';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and at the last line we see the &lt;code&gt;export default&lt;/code&gt;statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To understand these statements, let's discuss about modules syntax first.&lt;/p&gt;

&lt;p&gt;A module is simply a JavaScript file that exports one or more values (can be objects, functions or variables) using the export keyword. First, create a new file named &lt;code&gt;util.js&lt;/code&gt; in the &lt;code&gt;src&lt;/code&gt; directory&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;touch util.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then write a function inside it. This is a default export&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function times(x) {
  return x * x;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or multiple named exports&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
export function times(x) {
  return x * x;
}


export function plusTwo(number) {
  return number + 2;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we can import it from &lt;code&gt;src/App.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { times, plusTwo } from './util.js';

console.log(times(2));
console.log(plusTwo(3));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can have multiple named exports per module but only one default export. A default export can be imported without using the curly braces and corresponding exported function name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in util.js
export default function times(x) {
  return x * x;
}

// in app.js
import k from './util.js';

console.log(k(4)); // returns 16
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But for named exports, you must import using curly braces and the exact name. Alternatively, imports can use alias to avoid having the same name for two different imports:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in util.js
export function times(x) {
  return x * x;
}

export function plusTwo(number) {
  return number + 2;
}

// in app.js
import { times as multiplication, plusTwo as plus2 } from './util.js';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Import from absolute name like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Will make JavaScript check on &lt;code&gt;node_modules&lt;/code&gt;for the corresponding package name. So if you're importing a local file, don't forget to use the right path.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use in React&lt;/strong&gt;&lt;br&gt;
Obviously we've seen this in the &lt;code&gt;src/App.js&lt;/code&gt; file, and then in &lt;code&gt;index.js&lt;/code&gt; file where the exported &lt;code&gt;App&lt;/code&gt; component is being rendered. Let's ignore the serviceWorker part for now.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//index.js file

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(&amp;lt;App /&amp;gt;, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice how App is imported from &lt;code&gt;./App&lt;/code&gt; directory and the &lt;code&gt;.js&lt;/code&gt;extension has been omitted. We can leave out file extension only when importing JavaScript files, but we have to include it on other files, such as &lt;code&gt;.css&lt;/code&gt;. We also import another node module &lt;code&gt;react-dom&lt;/code&gt;, which enables us to render React component into HTML element.&lt;/p&gt;

&lt;p&gt;As for PWA, it's a feature to make React application works offline, but since it's disabled by default, there's no need to learn it in the beginning. It's better to learn PWA after you're confident enough building React user interfaces.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
The great thing about React is that it doesn't add any foreign abstraction layer on top of JavaScript as other web frameworks. That's why React becomes very popular with JS developers. It simply uses the best of JavaScript to make building user interfaces easier and maintainable. There really is more of JavaScript than React specifix syntax inside a React application, so once you understand JavaScript better — particularly ES6 — you can write React application with confident. But it doesn't mean you have to master everything about JavaScript to start writing React app. Go and write one now, and as opportunities come your way, you will be a better developer.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>react</category>
    </item>
    <item>
      <title>React State Management (2) : Redux</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Tue, 08 Mar 2022 15:13:22 +0000</pubDate>
      <link>https://dev.to/sananayab/react-state-management-2-redux-3e4a</link>
      <guid>https://dev.to/sananayab/react-state-management-2-redux-3e4a</guid>
      <description>&lt;p&gt;React state management: context API, Redux and Redux toolkit. The topic in this article is Redux.&lt;/p&gt;

&lt;p&gt;The chart below is the whole image of this practice application. Component A accepts user input text and passes it over to Component B as a prop. At the same time, dispatch the action to save the data in the store so that Component C and component D can use it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qiDeIrIn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4uosdud6dprt5dikp8vs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qiDeIrIn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4uosdud6dprt5dikp8vs.png" alt="Image description" width="880" height="571"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://redux.js.org/tutorials/fundamentals/part-1-overview#data-flow"&gt;Redux Fundamentals, Part 1: Redux Overview | Redux&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
      <category>redux</category>
    </item>
    <item>
      <title>Top 7 React Security Vulnerabilities</title>
      <dc:creator>sana</dc:creator>
      <pubDate>Mon, 07 Mar 2022 19:27:21 +0000</pubDate>
      <link>https://dev.to/sananayab/top-7-react-security-vulnerabilities-5d48</link>
      <guid>https://dev.to/sananayab/top-7-react-security-vulnerabilities-5d48</guid>
      <description>&lt;p&gt;React is one of the most widely used JavaScript libraries and front-end frameworks for creating user interfaces for web and mobile applications. It has a lot of benefits that set it apart from other JavaScript libraries like Vue.js. The following are a few of them: It is simple to maintain. Make a decent developer toolbox available. Produces reliable code Rendering that is faster React, like many other technologies, is not without flaws. Security is one of them. Unfortunately,&lt;br&gt;
Because of the growing demand for mobile apps and the shorter development cycles used by app development businesses, its security risks are frequently overlooked. According to Ponemon Institute research, 56% of security companies are unsure whether the application they designed will pass a security examination. With only a small portion of an organization’s resources dedicated to application security, we may see more app security flaws emerge from the applications they produce.&lt;br&gt;
As a result, it’s critical to be aware of the security flaws in the technology you’re utilizing to build your app. According to a research, the likelihood of React security problems being undiscovered grows exponentially with each new upgraded version of React or update to random libraries. As a result, knowing about React’s fundamental security issues is even more crucial for react developers.&lt;br&gt;
Vulnerabilities In Cybersecurity That You Should Be Aware Of:&lt;br&gt;
&lt;strong&gt;1. Cross-Site Scripting (Cross-Site Scripting)&lt;/strong&gt;:&lt;br&gt;
is a technique for React is preferred above other frameworks and libraries because of its universal rendering feature. Unfortunately, it’s also why it’s vulnerable to cross-site scripting assaults. To find security flaws in applications, attackers utilize complex automated scripts and crawlers. Once the vulnerability has been discovered, the cybercriminal will attempt to steal confidential information from a website through script injection. They aim to insert harmful code into your react application code, but there are techniques to safeguard your React app from cross-site scripting assaults.&lt;br&gt;
Use API createElement() because it can automatically detect malicious code injection&lt;br&gt;
Harness the power of JSX and benefit from auto escaping functionality to secure applications&lt;br&gt;
&lt;strong&gt;2. SQL and CSV Injection:&lt;/strong&gt;&lt;br&gt;
SQL injection is a sort of attack and web security flaw that updates data without the user’s knowledge. To extract data from the database, SQL code execution is required. It lets attackers to create new credentials, imitate authentic ones, and gain access to admin accounts, allowing them to access the system. SQL injections come in a variety of forms and shapes. The following are some of the most frequent SQL injection attacks that target React applications:&lt;br&gt;
Time-based SQL injections&lt;br&gt;
Error based SQL injections&lt;br&gt;
Logic-based SQL injections&lt;br&gt;
CSV injection, on the other hand, occurs when websites include untrusted inputs in their CSV files. Any cell that contains = will be deemed a formula by Microsoft Excel or any other spreadsheets tool when that CSV file is opened.&lt;br&gt;
&lt;strong&gt;3. Arbitrary Code Execution:&lt;/strong&gt;&lt;br&gt;
When an attacker wins arbitrary code execution rights on a process, they can run any code or command they choose. It’s a flaw in either the hardware or software that’s in charge of processing arbitrary code. Because these exploits are extremely vulnerable, they should be removed from services and applications used by the general public right away. Force programs to only read tokens established previously during development is one technique to solve this problem. By submitting a request to a server, the system can generate suitable headers. Developers must respond quickly to prevent such assaults, or their applications will become vulnerable.&lt;br&gt;
&lt;strong&gt;4. Server-Side Rendering Attack:&lt;/strong&gt;&lt;br&gt;
Developers may be required to render an application on the server-side in some cases. Regrettably, this increases the risk of data leakage. If your code uses JSON strings to convert data to strings, you should always be on the lookout for server-side rendering attacks. It will be more difficult to detect server-side rendering attacks if you have not detected the context data.&lt;br&gt;
&lt;strong&gt;5. Insecure Randomness:&lt;/strong&gt;&lt;br&gt;
User-supplied data is used for the majority of web applications. This enables cyber attackers to insert a link or code that begins with JavaScript, resulting in insecure randomization in the program. When a user clicks on that malicious link, the malicious script in the browser begins to run. Hackers will be able to retrieve sensitive data and even modify it if they have admin rights. When an attacker acquires complete control of uniform resource identifiers, the application as a whole becomes susceptible. Whitelisting protocol and HTML entities for link creation are the best ways to prevent this type of assault.&lt;br&gt;
&lt;strong&gt;6. Malicious Package:&lt;/strong&gt;&lt;br&gt;
What if a malicious version of React is published directly by an attacker?&lt;br&gt;
What if a hacker gets direct publish access to popular npm modules and uses them to distribute a harmful module? Apps created by developers using these modules will be insecure. A malicious module or package gathers data from your system and network and sends it to a third party, or it can run malicious malware during the installation process. To fool developers into downloading malicious packages, attackers utilize typosquatting, a technique that involves naming packages after their real-world equivalents. It can wreak havoc on your system once downloaded and installed.&lt;br&gt;
&lt;strong&gt;7. Zip Slip:&lt;/strong&gt;&lt;br&gt;
Zip slip is caused by a combination of rewritten arbitrary files and a directory traversal attack. For this, files can be extracted from the archive of a certain directory. When archive files are unzipped with a susceptible library, attackers have the potential to unzip a malicious file as well. Attackers can easily overwrite the file once the unzipping procedure is complete.&lt;br&gt;
Unfortunately, any sort of file, including executables, configuration files, and key system files, might be affected by this form of attack. In other words, an attacker can simply access arbitrary code from afar. When developers are using the same version of archive processing libraries, they can detect this type of assault. Once you’ve identified the flaw, you may put it through a directory traversal test and include zip slip in your security testing. These types of attacks can also be detected using dependency vulnerability detection techniques.&lt;br&gt;
More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>react</category>
    </item>
  </channel>
</rss>
