<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maissen Ayed on Medium]]></title>
        <description><![CDATA[Stories by Maissen Ayed on Medium]]></description>
        <link>https://medium.com/@bits-of-code?source=rss-343de517d8f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EKTH_C9E1lXG56Mx_mKPeA.jpeg</url>
            <title>Stories by Maissen Ayed on Medium</title>
            <link>https://medium.com/@bits-of-code?source=rss-343de517d8f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 08:07:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bits-of-code/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Things I’d Rather you Tell me]]></title>
            <link>https://bits-of-code.medium.com/the-things-id-rather-you-tell-me-4972c7fe486f?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4972c7fe486f</guid>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 07:29:08 GMT</pubDate>
            <atom:updated>2026-07-08T07:29:08.227Z</atom:updated>
            <content:encoded><![CDATA[<p>I see the bitter air that suffocates you,</p><p>That heavy, aching layer of extra skin.</p><p>But under the armor that bites when fed anew,</p><p>Is the most beautiful soul, trapped deep within.</p><p>Let me hold your hands when the swirling starts,</p><p>To soothe the dry and overwhelmed parts.</p><p>You are cherished, far beyond the doubt and fright,</p><p>And together, we will shed this skin into the light.</p><p>When you are frozen, unable to step or move,</p><p>Trapped in the dry winds of a springless land,</p><p>I will walk beside you through the frost and fog,</p><p>Catching you on the ice, holding tight your hand.</p><p>If the sun forgets to warm, and the moon withdraws its grace,</p><p>I will build a bonfire here, in this barren, aching place.</p><p>I will wait with you in the cold, unmoving, steadfast, true,</p><p>Standing by your side until the frozen lands melt into spring just for you.</p><p>You are no lost character in a play about to start,</p><p>But the greatest, brightest being that has ever lived and grown.</p><p>I love you to the end of the world, with all my beating heart,</p><p>Through every unresolved case, you will never be alone.</p><p>So when the untamed candor feels too heavy to convey,</p><p>And you are writing down the things you’d rather never say,</p><p>Pour your heavy emotions into me, let them safely spill</p><p>I will help you navigate the silence, and I always will.</p><p>Please pour your heavy emotions into me, let them safely spill</p><p>I will help you navigate the silence, and I always will.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4972c7fe486f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React fundamentals part 12: useRef()]]></title>
            <link>https://bits-of-code.medium.com/react-fundamentals-part-12-useref-8dd0bca2c2b0?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd0bca2c2b0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Wed, 01 May 2024 12:47:19 GMT</pubDate>
            <atom:updated>2024-05-03T12:03:06.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>What are references?</h3><p>When using React, you may require an escape hatch to write imperative-style code in order to interact directly with <strong>DOM</strong> elements. You can do this by using React’s <strong>createRef</strong> method!</p><p>React.createRef allows you to obtain references to <strong>DOM</strong> nodes (). It&#39;s really just a JavaScript equivalent of this all-too-familiar snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*u8b4wy7B5asEVgjJ" /></figure><p>This is exactly what React.createRef() does, although it requires a bit of a different setup.</p><pre>import React, { Component } from &#39;react&#39;;<br><br>class Component extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.myInput = React.createRef();    // initialize &quot;this.myInput&quot;  <br>  }<br>  <br>  render() {<br>    return (<br>      &lt;input ref={this.myInput}/&gt;        {/* pass &quot;this.myInput&quot; as ref */}<br>    );<br>  }<br>}</pre><p>When working with class-based components, we used createRef() to create a ref. However, since React now recommends functional components and general practice is to use <strong>Hooks</strong>, we no longer need to use createRef(). To create refs in functional components, we instead use useRef(null).</p><h3>What is useRef used for?</h3><p>The useRef Hook in React can be used to directly access DOM nodes, as well as persist a mutable value across rerenders of a component.</p><p>The basic signature for the useRef Hook looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jKLSbE6iizMlqF-w" /></figure><p>useRef returns a mutable object whose value is set as: {current: initialValue}.</p><h3>Mutable values</h3><p>The reference object is mutable, which means we can access the reference value using reference.current and update it by assigning reference.current to a new value or variable.</p><p>There are two important behaviours to remember about useRef() references:</p><ol><li>The reference value stays the same (persists) between component re-renders.</li><li>Updating a reference value does not re-render the component.</li></ol><p>The difference between using useRef and manually setting an object value directly within your component, e.g., const myObject = {current: initialValue}, is that the ref object remains the same all through the lifetime of the component, i.e., across re-renders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9PPy3PuO27rN5Pq6" /></figure><p>To update the value stored in the ref object, you go ahead and mutate the current property as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8_pb7DrCmS8TZKDl" /></figure><p>The returned object from invoking useRef will persist for the full lifetime of the component, regardless of re-renders.</p><h4>Example click count Logger</h4><pre>import { useRef } from &#39;react&#39;;<br>const countLogger = () =&gt; {<br>    const reference = useRef(0);<br><br>    const handleClick = () =&gt; {<br>        reference.current++;<br>        console.log(`${reference.current} button clicks`);<br>    }<br><br>    console.log(&quot;Component rendered&quot;);<br>    <br>    return (<br>        &lt;button onClick={handleClick}&gt;Click me!&lt;/button&gt;<br>    )<br>}</pre><p>const reference = useRef(0) creates a reference reference with an initial value of 0. This reference object is used to keep track of how many times a button has been clicked. The reference value is updated and logged to the console when you click the button. As you may have noticed in your console, &quot;Component rendered&quot; is only logged once (during the initial render), implying that button clicks, or more precisely, reference value updates, do not cause component re-renders.</p><h3>Directly access DOM nodes</h3><p>We could use <strong>useRef</strong> in conjunction with the ref attribute to obtain the underlying <strong>DOM</strong> nodes and perform <strong>DOM</strong> operations imperatively. In reality, this is an escape route. We should only do this sparingly for things like focus management, for which React does not provide a declarative API.</p><p>Declarative views are one of the many concepts popularized by React among developers. Prior to declarative views, most of us changed the <strong>DOM</strong> by calling functions that changed it explicitly.</p><p>We are now declaring views based on a state, and while we are still calling functions to change this state, we have no control over when or if the <strong>DOM</strong> will change.</p><p>If it weren’t for the refs, we’d lose this imperative nature due to the inversion of control.</p><p>A common use case for useRef is to manage child <strong>DOM</strong> nodes:</p><pre>function TextInputWithFocusButton() {<br>  //1. create a ref object with initialValue of null<br>  const inputRef = useRef(null);<br><br>  const onButtonClick = () =&gt; {<br>    // 4. `current` points to the mounted text input element<br>    // 5. Invoke the imperative focus method from the current property<br>    inputRef.current.focus();<br>  };<br><br>  return (<br>    &lt;&gt;<br>      {/* 2. as soon as input is rendered, the element will be saved in the ref object, i.e., {current: *dom node*}  */}<br>      &lt;input ref={inputRef} type=&quot;text&quot; /&gt;<br>      {/* 3. clicking the button invokes the onButtonClick handler above */}<br>      &lt;button onClick={onButtonClick}&gt;Focus the input&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>The example above works because if you pass a ref object to React, e.g., &lt;div ref={myRef} /&gt;, React will set its current property to the corresponding DOM node whenever that node changes, i.e., myRef = {current: *dom node*}.</p><p>useRef returns a plain JavaScript object, so it can be used for holding more than just DOM nodes.</p><p>It can hold whatever value you want. This makes it the perfect choice for simulating instance-like variables in functional components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/0*XGDoli_EqQkcZSQf" /></figure><p>In the example above, we log initialProp and prop via useEffect. This will be logged on mount and every time prop changes.</p><p>Since initialProp is prop saved on initial render, it never changes. It’ll always be the initial value of props. Here’s what we mean.</p><p>If prop passed to App were changed from <strong>1</strong> to <strong>5</strong> , coming from state update , the following will be logged:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1OSpx-EChU5WbZOI" /></figure><p>initialProp remains the same through the lifetime of the component because it is saved in the ref object. The only way to update this value is by mutating the current property of the ref object: initialProp.current = <em>*new value*</em>.</p><p>With this, you can go ahead and create <a href="https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables">instance-like variables</a> that don’t change within your functional component.</p><p>Remember, the only difference between useRef and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.</p><h3>Integrating with DOM-based libraries</h3><p>As good as React is, there are many utilities and libraries that have been in use on the web for years that are not part of its ecosystem. Using refs, for example, allows us to combine React with a fantastic animation library. It’s a good idea to use their stability and resolution for some specific problems.</p><p>The <a href="https://blog.logrocket.com/animations-react-hooks-greensock/">GSAP library</a> is a popular choice for animation examples. To use it, we need to send a DOM element to any of its methods.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhzp5pl%3Fview%3Deditor%2B%252B%2Bpreview%26module%3D%252Fsrc%252Fstyles.scss&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Feqbvug&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fhzp5pl%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/47b843cdac89bc359392752c88b72612/href">https://medium.com/media/47b843cdac89bc359392752c88b72612/href</a></iframe><p>When the element gets unmounted, we’ll clean the DOM state and actions by terminating any ongoing animation with the kill() method supplied by the Timeline instance.</p><h4>Ref is null on initial rendering</h4><p>During initial rendering, the reference supposed to hold the DOM element is empty:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fempty-on-initial-rendering-forked-4jlhq6%3Ffrom-embed%3D&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2Fempty-on-initial-rendering-forked-4jlhq6%3Ffrom-embed%3D&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F4jlhq6%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fb4e41228a2cf6405381aa214fa9e7c/href">https://medium.com/media/3fb4e41228a2cf6405381aa214fa9e7c/href</a></iframe><p>During initial rendering React still determines what is the output of the component, so there’s no DOM structure created yet. That’s why inputRef.current evaluates to undefined during initial rendering.</p><p>useEffect(callback, []) hook invokes the callback right after mounting, when the input element has already been created in DOM.</p><p>callback function of the useEffect(callback, []) is the right place to access inputRef.current because it is guaranteed that the DOM is constructed.</p><h3>Updating references restriction</h3><p>The function scope of the functional component should either calculate the output or invoke hooks.</p><p>That’s why updating a reference (as well as updating state) shouldn’t be performed inside the immediate scope of the component’s function.</p><p>The reference must be updated either inside a useEffect() callback or inside handlers (event handlers, timer handlers, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5UDW0Ryy5ctl3Epz" /></figure><blockquote>useRef vs. createRef</blockquote><blockquote><strong>createRef every time when it runs, it creates a new ref object.</strong></blockquote><blockquote><strong>useRef only creates a ref object for a particular <em>component instance</em> when it&#39;s first rendered. In the following rerenders, it&#39;ll just returns the existing ref object associated with that component instance. That&#39;s why we can trust it to persist a value across rerenders!</strong></blockquote><h3>Update state from ref</h3><p>There’s one more thing to note. useRef doesn’t notify you when its content changes, i.e., mutating the current property doesn’t cause a re-render. For cases such as performing a state update after React sets the current property to a DOM node, make <a href="https://maissen.gitbook.io/react-grimoire/react-hooks/usecallback">useCallback</a> ref as follows:</p><pre>function UpdateStateOnSetRef() {<br>  // set up local state to be updated when ref object is updated<br>  const [height, setHeight] = useState(0);<br><br>  // create an optimised callback via useCallback<br>  const measuredRef = useCallback(node =&gt; {<br>    // callback passed to &quot;ref&quot; will receive the DOM node as an argument<br>    if (node !== null) {<br>      // check that node isn&#39;t empty before calling state<br>      setHeight(node.getBoundingClientRect().height);<br>    }<br>  }, []);<br>  return (<br>    &lt;&gt;<br>      {/* pass callback to the DOM ref */}<br>      &lt;h1 ref={measuredRef}&gt;Hello, world&lt;/h1&gt;<br>      &lt;h2&gt;The above header is {Math.round(height)}px tall&lt;/h2&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Difference between state and references</h3><ol><li>Updating state does trigger component re-rendering but updating a reference does not.</li><li>The state update is asynchronous (the state variable is updated after re-rendering), while the reference update is synchronous.</li></ol><h3>forwardRef in React?</h3><p>So what is forwardRef, and why is it important?</p><p>Let’s start with an example: Let’s say we have an Input component in our React application that looks like the following:</p><pre>const Input = (props) =&gt; {<br>  return &lt;input {...props} /&gt;;<br>};</pre><p>Now, we also want to focus the input component on the click of a button.</p><p>To achieve that, we simply need to create a new reference in our app, pass it down to Input, and call .focus() on the element, right? Wrong!</p><p>By default, the ref prop <strong>only works on HTML elements</strong>, not on React components.</p><p>When we want to pass down a reference to a React component, <strong>we need to tell React which HTML element it should reference</strong>, as there can be more than one in our component.</p><p>That’s where forwardRef becomes useful. It allows us to specify which exact HTML element we want to reference.</p><h3>How to use forwardRef</h3><p>Our task is to forward the ref that the Input component receives to the HTML input element.</p><p>We do that by wrapping the component in forwardRef. The function accepts a callback with two parameters:</p><ol><li>The component props</li><li>The ref to be forwarded</li></ol><p>This callback is our function component, which now accepts a second property.</p><pre>const Input = forwardRef((props, ref) =&gt; {<br>  // Here goes the content of our component<br>});</pre><p>In the returned JSX code, we now need to pass the ref we receive in the function to the correct HTML component, which in our case is the input element.</p><pre>const Input = forwardRef((props, ref) =&gt; {<br>  return (<br>    &lt;input<br>      ref={ref}      {...props}<br>    /&gt;<br>  );<br>});</pre><p>Here’s the final code for doing so:</p><pre>import React, { useState, useRef, forwardRef } from &#39;React&#39;;<br><br>const Input = forwardRef((props, ref) =&gt; {<br>  return &lt;input ref={ref} {...props} /&gt;;<br>});<br>const App = () =&gt; {<br>  const inputRef = useRef(null);<br>  const [value, setValue] = useState(&#39;&#39;);<br>  const onInputChange = (e) =&gt; {<br>    e.preventDefault();<br>    setValue(e.target.value);<br>  };<br>  const focus = () =&gt; {<br>    inputRef.current?.focus();<br>  };<br>  return (<br>    &lt;&gt;<br>      &lt;Input value={value} onChange={onInputChange} ref={inputRef} /&gt;<br>      &lt;button onClick={focus}&gt;Focus&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><h4>Custom names for DevTools</h4><p>The forwardRef function <strong>takes the name of the component from the function</strong> it accepts as a parameter. If you&#39;re using anonymous or arrow functions, your DevTools will display the component like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*HqLR3-QdyTaBnLhb" /></figure><p>There are a few things you can do to avoid this. To begin, you could use a regular function expression with the following name:</p><pre>const Input = forwardRef(function Input(props, ref) {<br>  return &lt;input ref={ref} {...props} /&gt;;<br>});</pre><p>If, like me, you haven’t used this syntax in the last three years, you can manually set the display name by adding the following line to the end of the file:</p><pre>Input.displayName = &#39;Input&#39;;</pre><h3>References and articles :</h3><ul><li><a href="https://alexsidorenko.com/blog/react-render-refs/">A Visual Guide to React Rendering - Refs</a></li><li><a href="https://epicreact.dev/the-latest-ref-pattern-in-react/">The Latest Ref Pattern in React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd0bca2c2b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React fundamentals part 10 :useContext]]></title>
            <link>https://bits-of-code.medium.com/react-fundamentals-part-10-usecontext-a042fcfeb76b?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a042fcfeb76b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 08:51:11 GMT</pubDate>
            <atom:updated>2024-04-29T11:14:45.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>React fundamentals part 11 :useContext</h3><p>Context is React’s way of handling shared data between multiple components.</p><ul><li><a href="https://react.dev/learn/passing-data-deeply-with-context">Passing Data Deeply with Context - React</a></li><li><a href="https://react.dev/reference/react/useContext">useContext - React</a></li></ul><p>According to the React documentation, Context provides a way to pass data through the component tree from parent to child components without having to pass props down manually at each level.</p><p>Each component in Context is context-aware. Essentially, instead of passing props down through every single component on the tree, the components in need of a prop can simply ask for it, without needing intermediary helper components that only help relay the prop.</p><h3>API</h3><h4>React.createContext</h4><p>The createContext method is used to create a Context object to which components can subscribe. These components are able to get the context value from the closest matching Provider above them in the tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8c-orORQaM84L4dX" /></figure><p>Components are usually wrapped in a Provider in order to get their context value. However, when there’s no matching Provider above a component in the tree, the component will get its context from the default argument initialContext in the createContext method. This is especially useful when testing components in isolation.</p><h4>Context.Provider</h4><p>The React.createContext method will return a Provider component when it is called. Providers are React components from Context objects that allow other components to access those context values and subscribe to their changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*CZWK9QqzQ3wq8qND" /></figure><p>The Provider component accepts a value prop, which can then be accessed by its consuming child components. A Provider can have multiple child components or consumers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*olZIYpgSJ7dMTsG1" /></figure><p>Components will use the default context value from the createContext method when they have no matching parent Provider. However, once a Provider is available, even if its value prop is undefined, its child components or consumers will use its value.</p><p>Whenever a Provider’s value prop changes, its subscribed consumers will re-render.</p><p><strong>Consuming the context</strong></p><p>Consuming the context can be performed in 2 ways.</p><p>The first way, and the one I recommend, is to use the useContext(Context) React hook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*b_tBGJBNsVXXkSd9" /></figure><p>The hook returns the value of the context: value = useContext(Context). The hook also makes sure to re-render the component when the context value changes.</p><p>The second way is by using a render function supplied as a child to Context.Consumer special component available on the context instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_e3UVQtlZeV6zzaH" /></figure><p>Again, if the context value changes, &lt;Context.Consumer&gt; will re-render its render function.</p><p>useContext is invoked with a context object (the result of calling React.createContext), and it returns the current value for that context.</p><p>The value returned from useContext is determined by the value prop of the nearest Provider above the calling component in the tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nBo10i1nGR6nbI4O" /></figure><p>Note that using the useContext Hook within a component implicitly subscribes to the nearest Provider in the component tree, i.e., when the Provider updates, this Hook will trigger a rerender with the latest value passed to that Provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LVIG_Nvvv3IbmoRW" /></figure><p>Here’s an even more important point to remember:. If the ancestor component uses React.memo or shouldComponentUpdate(for class components), a re-render will still happen starting at the component that calls useContext.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Us2pALeNDTEZnzi1" /></figure><p>A component calling useContext will be re-rendered when the context value changes. If this is expensive, you may consider optimizing it by using <a href="https://github.com/facebook/react/issues/15156#issuecomment-474590693">memoization</a>.</p><p>Remember that useContext only lets you read the context and subscribe to its changes. You still need a context provider, i.e., ContextObject.Provider, above in the component tree to provide the value to be read by useContext.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KW4Wfv3-ZXNQBqTu" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hHz0L8J-OANXFdcb" /></figure><p>You can have as many consumers as you want for a single context. If the context value changes (by changing the value prop of the provider &lt;Context.Provider value={value} /&gt;), then all consumers are immediately notified and re-rendered.</p><p>If the consumer isn’t wrapped inside the provider, but still tries to access the context value (using useContext(Context) or &lt;Context.Consumer&gt;), then the value of the context would be the default value argument supplied to createContext(defaultValue) factory function that had created the context.</p><h3>Use case: global user name</h3><p>The simplest way to pass data from a parent to a child component is when the parent assigns props to its child component:</p><pre><br>function Application() {<br>  const userName = &quot;John Smith&quot;;<br>  return &lt;UserInfo userName={userName} /&gt;;<br>}<br><br>function UserInfo({ userName }) {<br>  return &lt;span&gt;{userName}&lt;/span&gt;;<br>}</pre><p>The parent component &lt;Application /&gt; assigns userName data to its child component &lt;UserInfo name={userName} /&gt; using the userName prop.</p><p>That’s the usual way data is passed using props. You can use this approach without problems.</p><p>The situation changes when &lt;UserInfo /&gt; child component isn&#39;t a direct child of &lt;Application /&gt; but is contained within multiple ancestors.</p><p>For example, let’s say that &lt;Application /&gt; component (the one having the global data userName) renders &lt;Layout /&gt; component, which in turn renders &lt;Header /&gt; component, which in turn finally renders &lt;UserInfo /&gt; component (that&#39;d like to access userName).</p><p>Here’s how such a structure would look:</p><p>You can see the problem: because &lt;UserInfo /&gt; component renders deep down in the tree, and all the parent components (&lt;Layout /&gt; and &lt;Header /&gt;) have to pass the userName prop.</p><p><a href="https://kentcdodds.com/blog/prop-drilling">Prop Drilling</a></p><p>React context is a possible solution. Let’s see how to apply it in the next section.</p><h4>3.1 Context to the rescue</h4><p>As a quick reminder, applying the React context requires 3 actors: the context, the provider extracted from the context, and the consumer.</p><p>Here’s how the sample application would look when applying the context to it:</p><p>Let’s look into more detail at what has been done.</p><p>First, const UserContext = createContext(&#39;&#39;) creates the context that&#39;s going to hold the user name information.</p><p>Second, inside the &lt;Application /&gt; component, the application&#39;s child components are wrapped inside the user context provider: &lt;UserContext.Provider value={userName}&gt;. Note that the value prop of the provider component is important: this is how you set the value of the context.</p><p>Finally, &lt;UserInfo /&gt; becomes the consumer of the context by using the built-in useContext(UserContext) hook. The hook is called with the context as an argument and returns the user name value.</p><p>&lt;Layout /&gt; and &lt;Header /&gt; intermediate components don&#39;t have to pass down the userName prop. That is the great benefit of the context: it removes the burden of passing down data through the intermediate components.</p><h4>3.2 When context changes</h4><p>When the context value is changed by altering value prop of the context provider (&lt;Context.Provider value={value} /&gt;), then all of its consumers are being notified and re-rendered.</p><p>For example, if I change the user name from &#39;John Smith&#39; to &#39;Smith, John Smith&#39;, then &lt;UserInfo /&gt; consumer immediately re-renders to display the latest context value:</p><p>The consumer that renders the context value on the screen, re-renders when the context value changes.</p><h4>4. Updating the context</h4><p>The React Context API is stateless by default and doesn’t provide a dedicated method to update the context value from consumer components.</p><p>But this can be easily implemented by integrating a state management mechanism (like useState() or useReducer() hooks), and providing an update function right in the context next to the value itself.</p><p>In the following example, &lt;Application /&gt; component uses useState() hook to manage the context value.</p><p>&lt;UserNameInput /&gt; consumer reads the context value, from where userName and setUserName are extracted. The consumer then can update the context value by invoking the update function setUserName(newContextValue).</p><p>&lt;UserInfo /&gt; is another consumer of the context. When &lt;UserNameInput /&gt; updates the context, this component is updated too.</p><p>Note that &lt;Application /&gt; memoizes the context value. Memoization keeps the context value object the same as long as userName is the same, preventing re-rendering of consumers every time the &lt;Application /&gt; re-renders.</p><p>Otherwise, without memoization, const value = { userName, setUserName } would create different object instances during re-rendering of &lt;Application /&gt;, triggering re-rendering in context consumers.</p><h3>Global shared state with React Context</h3><p>Another use case for React Context is using it as a global state mechanism, like we have in between TopNav and Profile. Updating the username in Profile immediately updates the shared state in UserProvider, providing a mechanism for global state management.</p><p>As with prop drilling, there can be some performance drain when using Context. Whenever it renders, its child components also render. One way to minimize rendering is to keep Context as close to where it’s being used as possible, like we’ve done with UserProvider. Although we could position it higher up in the component tree, it would be less effective.</p><h3>What the React Context API is used for?</h3><p>With React Context, we can pass data deeply. While some developers may want to use Context as a global state management solution, doing so is tricky. While React Context is native and simple, it isn’t a dedicated state management tool like Redux, and it doesn’t come with sensible defaults.</p><p>If you decide to use React Context at all, you should be aware of its potential for performance drain. You can very easily get carried away and add too many components where they aren’t needed. To prevent re-rendering, be sure to place contexts correctly only in the components that require them.</p><p>The main idea of using context is to allow your components to access some global data and re-render when that global data is changed. Context solves the props drilling problem: when you have to pass down props from parents to children.</p><p>You can hold inside the context:</p><ul><li>theme</li><li>application configuration</li><li>authentication information</li><li>user settings</li><li>preferred language</li><li>a collection of services</li></ul><p>On the other side, you should think carefully before deciding to use context in your application.</p><p>First, integrating the context adds complexity. Creating the context, wrapping everything in the provider, and using the useContext() in every consumer — this increases complexity.</p><p>Secondly, adding context makes it more difficult to unit test the components. During unit testing, you would have to wrap the consumer components into a context provider. Including the components that are indirectly affected by the context — the ancestors of context consumers!</p><h3>Redux vs. the React Context API</h3><p>Does React Context replace Redux? The short answer is no, it doesn’t. As we’ve seen, Context and Redux are two different tools, and comparison often arises from misconceptions about what each tool is designed for.</p><p>Although Context can be orchestrated to act as a state management tool, it wasn’t designed for that purpose, so you’d have to do put in extra effort to make it work. There are already a lot of state management tools that work well and will ease your troubles.</p><p>In my experience with Redux, it can be relatively complex to achieve something that is easier to solve today with Context. Keep in mind, prop drilling and global state management are where Redux and Context’s paths cross. Redux has more functionality in this area.</p><p>Ultimately, Redux and Context should be considered complementary tools that work together instead of alternatives. My recommendation is to use Redux for complex global state management and Context for prop drilling.</p><p>You can find more from the creator of redux himself.</p><p><a href="https://blog.isquaredsoftware.com/2018/03/redux-not-dead-yet/">Blogged Answers: Redux - Not Dead Yet!</a></p><h3>SSR Read only data</h3><p>If you are using SSR, for each page, you will get a full list of data that is read only. It can be configuration values, meta information for the page, or any data that we fetch and already get from the server in the first mount and don’t mutate (the user doesn’t edit or modify it in the life span of the page).</p><p>This case is one of my favorites for context.<br>We are sure that the data that we want to pass will never change, and it’s read-only information. Therefore, the context will never re-render as a whole.<br>With that, we can remove at least the prop drilling for these data from the app.</p><h3>References and articles :</h3><ul><li><a href="https://blog.logrocket.com/pitfalls-of-overusing-react-context/">Pitfalls of overusing React Context - LogRocket Blog</a></li><li><a href="https://kentcdodds.com/blog/how-to-use-react-context-effectively">How to use React Context effectively</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1kFX3B2IyH0%3Fstart%3D3%26feature%3Doembed%26start%3D3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1kFX3B2IyH0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1kFX3B2IyH0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/39aac96ff3fa9f9337aeb0b81af212df/href">https://medium.com/media/39aac96ff3fa9f9337aeb0b81af212df/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMpdFj8MEuJA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMpdFj8MEuJA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMpdFj8MEuJA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/df962d0a5f2a76068d263d3ee0fa3c5d/href">https://medium.com/media/df962d0a5f2a76068d263d3ee0fa3c5d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a042fcfeb76b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React fundamentals part 10 : useEffect]]></title>
            <link>https://bits-of-code.medium.com/react-fundamentals-useeffect-85a75ccb1cec?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/85a75ccb1cec</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[side-effects]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 18:02:47 GMT</pubDate>
            <atom:updated>2024-04-13T12:10:42.357Z</atom:updated>
            <content:encoded><![CDATA[<p>React.useEffect is an in-built <strong>hook</strong> that lets you run custom code after React renders (and re-renders) your component to the <strong>DOM</strong>. It accepts a callback function that React will call after the <strong>DOM</strong> has been rendered, but first, let&#39;s define an effect.</p><h3>What are effects?</h3><p>The term “Side Effect” does not refer to a specific reaction. It is a broad concept referring to the behaviors of functions. If a function attempts to modify anything outside of its body, it is said to have a side effect. It is a side effect, for example, if it modifies a global variable. It is also a side effect if it makes a network call.</p><p><a href="https://en.m.wikipedia.org/wiki/Side_effect_(computer_science)">Side effect (computer science) - Wikipedia</a></p><p>Side effects are defined as anything that has an effect on something that is not within the scope of the current function being executed.</p><h3>React side Effect</h3><p>However, there are times when we need our components to interact with APIs that are not part of the data-flow process. A side effect is an action that has an impact on the outside world in some way. The following are common side effects:</p><ul><li>handling subscriptions with event listeners.</li><li>dealing with manual <strong>DOM</strong> changes.</li><li>Logging messages to the console or other service.</li><li>Setting or getting values in local storage.</li><li>Fetching data or subscribing and unsubscribing to services.</li></ul><p><a href="https://reactjs.org/docs/hooks-reference.html#useeffect">useEffect</a> is a hook to let you invoke side effects from within functional components,</p><p>The basic signature of useEffect is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/0*FPB4aTFmIkMo_uK1" /></figure><p>Let’s analyse this example</p><pre>import * as React from &quot;react&quot;;<br><br>const BasicEffect = () =&gt; {<br>  const [counter, setCounter] = React.useState(0);<br>  const handleClick = () =&gt; setCounter((prev) =&gt; prev + 1);<br>  <br>  React.useEffect(() =&gt; {<br>    handleClick();<br>  });<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;span&gt; {`Counter is ${counter}`} &lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>As we can see, <strong>useEffect</strong> will force the component to redraw because it is always invoked after each redraw, so when the counter is updated, <strong>useEffect</strong> will invoke <strong>handleClick</strong>, and we will be in an infinite loop.</p><h3>Empty dependency array</h3><p>It is also possible to add an empty dependency array. In this case, effects are only executed once; it is similar to the <a href="https://reactjs.org/docs/react-component.html#componentdidmount">componentDidMount()</a> lifecycle method. (similar but not exactly the same)</p><pre>import * as React from &quot;react&quot;;<br>  <br>const BasicEffect = () =&gt; {<br>  const [counter, setCounter] = React.useState(0);<br>  const handleClick = () =&gt; setCounter((prev) =&gt; prev + 1);<br>  <br>  React.useEffect(() =&gt; {<br>    handleClick();<br>  },[]);<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;span&gt; {`Counter is ${counter}`} &lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p><strong>useEffect is passed an empty array, </strong><strong>[]. Hence, the effect function will be called only on mount</strong></p><h3>Triggering Effect</h3><p>Let’s take this example</p><pre>import * as React from &quot;react&quot;;<br><br><br>const BasicEffect = () =&gt; {<br>  const [counter, setCounter] = React.useState(0);<br>  const handleClick = () =&gt; setCounter((prev) =&gt; prev + 1);<br>  <br>  React.useEffect(() =&gt; {<br>    handleClick();<br>  },[count]);<br>  <br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;span&gt; {`Counter is ${counter}`} &lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>We still have an infinite loop , but why is that?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UXcunSpsZBdB5SKQ" /></figure><p>The dependency array basically tells the hook to “only trigger when the dependency array changes”. In the above example, it means “run the callback every time the counter variable changes&quot;.</p><p>If you have multiple elements in a dependency array, the hook will trigger if <em>any</em> element of the dependency array changes.</p><h3>Skipping effects</h3><pre>const ArrayDepMount = () =&gt; {<br>  const [randomNumber, setRandomNumber] = useState(0)<br>  const [effectLogs, setEffectLogs] = useState([])<br><br>  useEffect(<br>    () =&gt; {<br>      setEffectLogs(prevEffectLogs =&gt; [...prevEffectLogs, &#39;effect fn has been invoked&#39;])<br>    },<br>    [randomNumber]<br>  )<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{randomNumber}&lt;/h1&gt;<br>      &lt;button<br>        onClick={() =&gt; {<br>          setRandomNumber(Math.random())<br>        }}<br>      &gt;<br>        Generate random number!<br>      &lt;/button&gt;<br>      &lt;div&gt;<br>        {effectLogs.map((effect, index) =&gt; (<br>          &lt;div key={index}&gt;{&#39;🍔&#39;.repeat(index) + effect}&lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>We can see that the effect is dependent on the randomNumber state and will only be triggered if the randomNumber value has changed.</p><p><strong>If your effect is dependent on a state or prop value in scope, make sure to pass it as an array dependency to avoid accessing stale values within the callback. If the values referenced change over time and are used in the callback, include them in the array dependency.</strong></p><p>The React team recommends you use the <a href="https://www.npmjs.com/package/eslint-plugin-react-hooks#installation">eslint-plugin-react-hooks</a> package. It warns when dependencies are specified incorrectly and suggests a fix.</p><h3>The importance of the dependency array</h3><blockquote><strong>If no dependency array is provided, every scheduled useEffect is executed. This means that after each render cycle, each effect defined in the corresponding component is executed in the order specified in the source code.</strong></blockquote><blockquote><strong>As a result, the order of your effect definitions is important. In our case, whenever one of the state variables changes, our single useEffect statement is executed. In the source code, sitioning is used.</strong></blockquote><blockquote><strong>As array entries, you provide. React only executes the useEffect statement in these cases if at least one of the provided dependencies has changed since the previous run. In other words, the dependency array makes the execution conditional on certain conditions.</strong></blockquote><blockquote><strong>Most of the time, this is what we want; we usually want to execute side effects when certain conditions are met, such as when data changes, a prop changes, or the user first sees our component.</strong></blockquote><h3>Multiple effects</h3><p>Multiple useEffect calls can happen within a functional component, as shown below:</p><pre>const MultipleEffects = () =&gt; {<br>  // ⏬ <br>  useEffect(() =&gt; {<br>    const clicked = () =&gt; console.log(&#39;window clicked&#39;)<br>    window.addEventListener(&#39;click&#39;, clicked)<br>    <br>    return () =&gt; {<br>      window.removeEventListener(&#39;click&#39;, clicked)<br>    }<br>  }, [])<br><br>  // ⏬  another useEffect hook <br>  useEffect(() =&gt; {<br>    console.log(&quot;another useEffect call&quot;);<br>  })<br>  <br>  return &lt;div&gt;<br>    Check your console logs<br>  &lt;/div&gt;<br>}</pre><p>Note that useEffect calls can be skipped, not invoked on every render. This is done by passing a second array argument to the effect function.</p><h3>Cleaning up an effect</h3><p>The application of React By cleaning up effects, the effect cleanup function protects applications from undesirable behaviours such as memory leaks. We can improve the performance of our application by doing so.</p><h3>What is the useEffect cleanup function?</h3><p>The <strong>useEffect</strong> cleanup function, as the name implies, allows us to clean up our code before our component unmounts. When our code runs and reruns for each render, <strong>useEffect</strong> uses the cleanup function to clean up after itself.</p><p>The <strong>useEffect</strong> Hook is designed in such a way that we can return a function from within it, and it is within this return function that the cleanup occurs. The cleanup function prevents memory leaks and eliminates some unwanted and unnecessary behaviors.</p><p>Note that you don’t update the state inside the return function either:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*8Zey8JGbya4QZdai" /></figure><h3>Why is the useEffect cleanup function useful?</h3><p>As previously stated, the <strong>useEffect</strong> cleanup function assists developers in cleaning up effects that prevent unwanted behaviors and improve application performance.</p><p>It is important to note, however, that the useEffect cleanup function runs not only when our component wants to unmount, but also right before the execution of the next scheduled effect.</p><p>In fact, the next scheduled effect is usually based on the dependency array after our effect has completed.</p><p>As a result, whenever our effect is dependent on our prop or whenever we set up something that persists, we have a reason to invoke the cleanup function.</p><p>Consider the following scenario: suppose we receive a <strong>fetch</strong> of a specific user via a <strong>user’s id </strong>and, before the fetch is completed, we change our mind and attempt to obtain another user.</p><p>While the previous fetch request is still in progress, the <strong>prop</strong>, or in this case, the<strong> id</strong>, updates. To avoid exposing our application to a memory leak, we must abort the fetch using the cleanup function.</p><h3>When should we use the useEffect cleanup?</h3><p>Let’s say we have a React component that fetches and renders data. If our component unmounts before our promise resolves, useEffect will try to update the state (on an unmounted component) and send an error that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*glsaGXLEQzBmma6M" /></figure><p>Warning Error</p><p>To fix this error, we use the cleanup function to resolve it.</p><p><em>&quot;React performs the cleanup when the component unmounts&quot;</em> according to the official documentation. However, effects are applied to each render, not just the first. This is why React also cleans up effects from previous renders before running them again.&quot;</p><p>The cleanup is commonly used to cancel all subscriptions made and cancel fetch requests.</p><p><a href="https://alexsidorenko.com/blog/useeffect-cleanups/">A Visual Guide to useEffect - Cleanups</a></p><h3>Fetch Data from an API</h3><h3>Create the asynchronous function</h3><p>Then, let’s create an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">asynchronous function</a> to fetch our data. An asynchronous function is one that needs to wait after the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a> is resolved before continuing. In our case, the function will need to wait after the data is fetched (our promise) before continuing.</p><pre>const fetchData = async (url) =&gt; {<br>    try {<br>        const response = await fetch(url);<br>        const json = await response.json();<br><br>        console.log(json);<br>    } catch (error) {<br>        console.log(&quot;error&quot;, error);<br>    }<br>};</pre><p>Put the <strong>fetchData</strong> function above in the <strong>useEffect</strong> hook and call it, like so:</p><pre>useEffect(() =&gt; {<br>    // advice free ap<br>    const url = &quot;https://api.adviceslip.com/advice&quot;;<br>    <br>    const fetchData = async () =&gt; {<br>      try {<br>        const response = await fetch(url);<br>        const json = await response.json();<br>        console.log(json);<br>      } catch (error) {<br>        console.log(&quot;error&quot;, error);<br>      }<br>    };<br>    <br>    fetchData();<br>}, []);</pre><p>The function we just created is wrapped in a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">try…catch statement</a> so that the function catches the errors and prints them in the console. This helps debug and prevents the app from crashing unexpectedly.</p><p>Inside of the try, we are using the built-in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch API from JavaScript</a> to get the advice from the Advice Slip JSON API. We put the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await">await</a> keyword just in front of it to tell the function to wait for the fetch task to be done before running the next line of code.</p><p>Once we get a response, we are parsing it using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Body/json">.json() function</a>, meaning that we are transforming the response into JSON data that we can easily read. Then, we are printing the JSON data in the console.</p><p>Then, instead of printing the advice in the console, we’ll save it in the advice state.</p><pre>const [advice, setAdvice] = useState(&quot;&quot;)<br>setAdvice(json.slip.advice)</pre><h3>References and articles :</h3><ul><li><a href="https://alexsidorenko.com/blog/useeffect/">A Visual Guide to useEffect</a></li><li><a href="https://overreacted.io/a-complete-guide-to-useeffect/">A Complete Guide to useEffect - overreacted</a></li><li><a href="https://blog.logrocket.com/useeffect-react-hook-complete-guide/">A complete guide to the useEffect React Hook - LogRocket Blog</a></li><li><a href="https://academind.com/tutorials/useeffect-abort-http-requests">useEffect(), Http Requests &amp; Aborting</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-call-web-apis-with-the-useeffect-hook-in-react">How To Call Web APIs with the useEffect Hook in React | DigitalOcean</a></li><li><a href="https://devtrium.com/posts/async-functions-useeffect">How to use async functions in useEffect (with examples) - Devtrium</a></li><li><a href="https://epicreact.dev/myths-about-useeffect/">Myths about useEffect</a></li><li><a href="https://kentcdodds.com/blog/react-hooks-pitfalls">5 Tips to Help You Avoid React Hooks Pitfalls</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85a75ccb1cec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Fundamentals part 9: useState]]></title>
            <link>https://bits-of-code.medium.com/react-fundamentals-part-8-usestate-c1f82c3509f7?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1f82c3509f7</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 11:00:15 GMT</pubDate>
            <atom:updated>2024-04-07T17:18:24.914Z</atom:updated>
            <content:encoded><![CDATA[<p>The all-mighty state</p><p>The signature for the useState Hook is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*43q0i9YKc00MtkxG" /></figure><p>Here, state and setState refer to the state value and updater function returned on invoking useState with some initialState.</p><p>It’s important to note that when your component first renders and invokes useState, the initialState is the returned state from useState.</p><h3>Declare State Variable</h3><blockquote><strong>Always remember that the value of the state is always the initial state value on the first render</strong></blockquote><pre>const [state] = useState(100)<br> return &lt;div&gt; State variable is {state}&lt;/div&gt;</pre><h3>Update State Variable</h3><p>Also, to update state, the state updater function setState should be invoked with a new state value, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*chViPjvP-Gu1hDDh" /></figure><p>By doing this, a new re-render of the component is queued. useState guarantees that the state value will always be the most recent after applying updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qzjPT-YsJooL_NRaO8Z-GQ.gif" /></figure><p>For referential checks, the setState function’s reference never changes during re-renders.</p><blockquote><strong>If you try to update state with the same value as the current state, React won’t render the component children or fire effects, e.g., </strong><strong>useEffect callbacks. React compares previous and current state via the </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description"><strong>Object.is comparison algorithm</strong></a><strong>; if they are equal, it ignores the re-render.</strong></blockquote><blockquote><em>It’s important to note that in some cases, React may still render the specific component whose state was updated. That’s OK because React will not go deeper into the tree, i.e., render the component’s children.</em></blockquote><p>Here is an example of a Counter component that use useState to update the counter by one for each click</p><pre>const Counter = () =&gt; {<br>  const [counter, setCounter] = useState(0)<br>  const handleClick = () =&gt; setCounter(counter + 1)<br>  <br>  return (<br>    &lt;div&gt;<br>      Counter:{counter}<br>      &lt;div&gt;<br>        &lt;button onClick={handleClick}&gt;add to the counter &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Functional updates</h3><p>The state setter function returned by useState can be invoked in two ways. The first is by passing a new value directly as an argument:</p><pre>const [state, setState] = useState(initialStateValue)<br>...<br>// update state as follows<br>setState(newStateValue)</pre><p>This is correct and works perfectly in most cases. However, there are cases where a different form of state update is preferred: <strong><em>functional updates</em></strong>.</p><p>Here’s the example above revised to use the functional update form:</p><pre>const [state, setState] = useState(initialStateValue)<br><br>...<br>// update state as follows<br>setState((previousStateValue) =&gt; newValue)</pre><p>You pass a function argument to setState. Internally, React will invoke this function with the previous state as an argument. Whatever is returned from this function is set as the new state.</p><p>When your new state depends on the previous state value — e.g., a computation — favor the functional state update. Since setState is async, React guarantees that the previous state value is accurate.</p><p>Here’s an example:</p><pre>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  return (<br>    &lt;&gt;<br>      &lt;p&gt;Count value is: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(0)}&gt;Reset&lt;/button&gt;<br>      &lt;button <br>        onClick={() =&gt; setCount(prevCount =&gt; prevCount + 1)}&gt;<br>        Plus (+)<br>      &lt;/button&gt;<br>      &lt;button <br>        onClick={() =&gt; setCount(prevCount =&gt; prevCount - 1)}&gt;<br>       Minus (-)<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>In the example above, the button grows every time it’s clicked. Since the new state value depends on the old, the functional update form of setState is preferred.</p><h3>Lazily initializing state</h3><p>The initialState argument to useState is only used during your initial render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SyizPDWFRTQplJHD" /></figure><pre>// subsequent prop updates are ignored <br>const App = ({myProp}) =&gt; {<br>  const [state, setState] = useState(myProp)<br>}<br>// only the initial myProp value on initial render is passed as initialState. subsequent updates are ignored.</pre><h3>Initialize state from function</h3><p>If the initial state is a result of an expensive computation, you could also pass a function, which will be invoked only on initial render:</p><pre>const [state, setState] = useState(() =&gt; yourExpensiveComputation(props))</pre><p>As opposed to just passing an initial state value, state could also be initialized from a function, as shown below:</p><pre>const Component = () =&gt; {<br>  <br>  const [token] = useState(() =&gt; {<br>  // this will only render in first initial render<br>    const token = window.localStorage.getItem(&quot;sensetive-data&quot;);<br>    return token || &quot;please don&#39;t put sensetive data in local storage 😢😢😢😢&quot;<br>  })<br>  <br>  return &lt;div&gt;Token is {token}&lt;/div&gt;<br>}</pre><h3>Use with objects</h3><p>As opposed to strings and numbers, you could also use an object as the initial value passed to useState.</p><p>Note that you have to pass the entire object to the useState updater function because the object is replaced, not merged.This is very different from how this.setState worked in classes!</p><pre>function Component() {<br>  const [state, setState] = useState({ name: &quot;Mayssa&quot; });<br>  const updateState = () =&gt; setState({ occupation: &quot;Teacher&quot; });<br><br>  return (<br>    &lt;&gt;<br>      &lt;pre&gt;{JSON.stringify(state)}&lt;/pre&gt;<br>      &lt;button onClick={updateState}&gt;update state&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>So in order to add a property to the object, we’re using the ES6 spread operator ... to copy the existing properties into the new object,</p><pre>const updateState = () =&gt; { setState((prevState) =&gt; ({ ...prevState, occupation: &quot;Teacher&quot; })); };</pre><p>Pass a function to setState and return a merged object by using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread operator</a> (which<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign">Object.assign also works</a>).</p><h3>Use with arrays</h3><p>Remember: state can hold any kind of value! Here’s an example of useState holding an array.</p><p>Typing into the box and hitting Enter will add an item to the list.</p><pre>function ListOfThings() {<br>  const [itemsList, setItemsList] = useState([]);<br>  const [itemName, setItemName] = useState(&quot;&quot;);<br><br>  const addItem = event =&gt; {<br>    event.preventDefault();<br>    setItemsList([<br>      ...itemsList,<br>      {<br>        id: itemsList.length, // just for the sake of the example , never put the index of the item in the array as an id<br>        name: itemName<br>      }<br>    ]);<br>    setItemName(&quot;&quot;);<br>  };<br><br> return (<br>    &lt;&gt;<br>      &lt;form onSubmit={addItem}&gt;<br>        &lt;label&gt;<br>          &lt;input<br>            name=&quot;item&quot;<br>            type=&quot;text&quot;<br>            value={itemName}<br>            onChange={e =&gt; setItemName(e.target.value)}<br>          /&gt;<br>        &lt;/label&gt;<br>      &lt;/form&gt;<br>      &lt;ul&gt;<br>        {itemsList.map(item =&gt; (<br>          &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Notice we’re calling useState with an initial value of an empty array [],</p><p>For objects, in order to add an item to the array, we’re using the ES6 spread operator ... to copy the existing items into the new array, and inserting the new item at the end.</p><h3>Multiple calls to useState</h3><p>If you want to store multiple values in a function component, you’ve got a couple options:</p><ul><li>call useState more than once</li><li>shove everything into an object</li></ul><p>There’s nothing wrong with calling useState multiple times, and in most cases, that’s how I store multiple values. Once you get over 4 or 5 useState calls, it gets a bit unwieldy, but if you’re fine with it, React is too.</p><p>Multiple state variables may be used and updated from within a functional component, as shown below:</p><pre>const Component =() =&gt; {<br>  const [age, setAge] = useState(5)<br><br>  const [siblingsNumber, setSiblingsNumber] = useState(1)<br><br>  const handleAge = () =&gt; setAge(age + 1)<br><br>  const handleSiblingsNumber = () =&gt; <br>      setSiblingsNumber(siblingsNumber + 1)<br> <br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Today I am {age} Years of Age&lt;/p&gt;<br>      &lt;p&gt;I have {siblingsNum Multiple state variables may be used and updated from within a functional component as shown below:} siblings&lt;/p&gt;<br>      &lt;div&gt;<br>        &lt;button onClick={handleAge}&gt;<br>          Get older! <br>        &lt;/button&gt;<br>        &lt;button onClick={handleSiblingsNumber}&gt;<br>            More siblings! <br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>If expensive calculations are done within the body of your functional component, i.e., before the return statement, consider optimising these with <a href="https://react.dev/reference/react/useMemo">useMemo</a>.</p><p>References and articles :</p><p><a href="https://juejin.cn/post/6844903833764642830">从源码剖析useState的执行过程 — 掘金</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1f82c3509f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Fundamentals part 8: Handling Events]]></title>
            <link>https://bits-of-code.medium.com/react-fundamentals-part-8-handling-events-db9d96a9f2c8?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/db9d96a9f2c8</guid>
            <category><![CDATA[events]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 09:18:33 GMT</pubDate>
            <atom:updated>2024-03-24T09:18:33.163Z</atom:updated>
            <content:encoded><![CDATA[<p>Handling events with <strong>React</strong> elements is very similar to handling events on <strong>DOM</strong> elements. There are some syntax differences</p><ul><li><strong>React</strong> events are named using <strong>camelCase</strong>, rather than <strong>lowercase</strong>.</li><li>With <strong>JSX</strong> you pass a function as the event handler, rather than a string.</li></ul><p>In the <strong>JavaScript</strong> community, these handler functions are sometimes called <strong>callback functions</strong>, or <strong>callbacks</strong> for short (but this is really just a fancy way of saying <em>function</em>.) For example, you could use a callback to verify if a button is clicked</p><pre>&lt;button onClick={() =&gt; alert(&quot;I&#39;m clicked&quot;)}&gt;Click me&lt;/button&gt;</pre><h3>Event props</h3><p><strong>React’s</strong> event props are named after <strong>DOM</strong> events from raw <strong>JavaScript</strong>. For example, the onClick prop from the above example is named after the <a href="https://developer.mozilla.org/en-US/docs/Web/Events/click">DOM click event</a>. If you’ve used <strong>jQuery</strong> or raw <strong>JavaScript</strong> before, <strong>React’s</strong> events will feel familiar.</p><p>React has props for most DOM events. For example:</p><ul><li>onClick and onMouseMove can be used with any <strong>HTML</strong> element</li><li>onKeyDown and onFocus can be used with focusable elements</li><li>onSubmit can be used with &lt;form&gt; elements</li></ul><h3>Event Objects</h3><p>Whenever <strong>React</strong> calls an event <strong>callback</strong>, it passes a single argument that holds the <strong>event object</strong>.</p><pre>&lt;select id=&quot;cars Select&quot;<br>    onChange={(event) =&gt; {<br>        console.log(event);        <br>    }}&gt;<br>    &lt;option value=&quot;Audi&quot;&gt;Audi&lt;/option&gt;<br>    &lt;option value=&quot;BMW&quot;&gt;BMW&lt;/option&gt;<br>    &lt;option value=&quot;Mercedes&quot;&gt;Mercedes&lt;/option&gt;<br>    &lt;option value=&quot;Volvo&quot;&gt;Volvo&lt;/option&gt;<br>&lt;/select&gt;</pre><p>Here, event is a synthetic event. <strong>React</strong> defines these synthetic events according to the <a href="https://www.w3.org/TR/DOM-Level-3-Events/">W3C spec</a>, so you don’t need to worry about cross-browser compatibility. <strong>React</strong> events do not work exactly the same as native events. See the <a href="https://react.dev/reference/react-dom/components/common#react-event-object">SyntheticEvent </a>reference guide to learn more.</p><h3>Keyboard</h3><p><strong>Keyboard</strong> events can be used with any focusable element. This includes <strong>HTML</strong> form elements, as well as any element with a tabIndex property.</p><p>• onKeyDown is called when a key is depressed • onKeyPress is called after the key is released, but before onKeyUp is triggered • onKeyUp is called last, after the key is pressed</p><p>To check the key that was pressed, use the key property. This holds a string that represents the key.</p><blockquote>The altKey, ctrlKey, metaKey and shiftKey properties let you check if a modifier key was pressed at the time of the event. These are all booleans.</blockquote><p>A numeric keyCode property is also available, but try to avoid this as it will make your code harder to read.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fvitejs-vite-tenbjt%3Fembed%3D1%26file%3Dsrc%252Fcomponent%252FKeyboard.jsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fvitejs-vite-tenbjt%3Fembed%3D1%26file%3Dsrc%252Fcomponent%252FKeyboard.jsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fvitejs-vite-tenbjt%2F8738fb0bc360bbb054059d1b9d5f254c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/539e19a5a43426cdc93012a8f3adb422/href">https://medium.com/media/539e19a5a43426cdc93012a8f3adb422/href</a></iframe><h3>Focus</h3><p>• onBlur is called when a control loses focus • onFocus is called when a control receives focus</p><p>When switching between elements, onBlur will always be called before onFocus.</p><blockquote>It is probably best to avoid the event object for focus events, as browser support for the underlying events varies significantly. In particular, the preventDefault() method will not work reliably.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fvitejs-vite-tenbjt%3Fembed%3D1%26file%3Dsrc%252Fcomponent%252FFocus.jsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fvitejs-vite-tenbjt%3Fembed%3D1%26file%3Dsrc%252Fcomponent%252FFocus.jsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fvitejs-vite-tenbjt%2F4fcc6a80c29416a55460d866b4c7f99b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/19a4748b121186e319378a42017d2826/href">https://medium.com/media/19a4748b121186e319378a42017d2826/href</a></iframe><h3>Mouse</h3><p>• onClick: a mouse button was pressed and released. Called before onMouseUp. • onContextMenu: the right mouse button was pressed. • onDoubleClick • onMouseDown: a mouse button is depressed • onMouseEnter: the mouse moves over an element or its children • onMouseLeave: the mouse leaves an element • onMouseMove • onMouseOut: the mouse moves off of an element, or onto one of its children • onMouseOver: the mouse moves directly over an element • onMouseUp: a mouse button was released</p><p><strong>React’s</strong> drag and drop events have access to the same event object properties as the <strong>mouse</strong> events. However, I’d recommend using <a href="https://github.com/react-dnd/react-dnd">react-dnd</a> instead of using the raw events where possible. For reference, the drag/drop events are:</p><p>onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop</p><p>The button property holds a number that represents which <strong>mouse</strong> button was pressed. This will be 0 for the left button and 1 for the middle button. Theoretically, 2 represents the right button, but most browsers will not trigger any events other than onContextMenu when the right button is pressed.</p><p>The properties altKey, ctrlKey, metaKey and shiftKey allow you to check if a modifier key was pressed on your <strong>keyboard</strong> when the event was triggered, just like with <strong>keyboard</strong> events. These are all booleans.</p><p>The preventDefault() method can be used to cancel default click actions. For example, to prevent the browser from navigating when a link is clicked, you can call event.preventDefault() within an &lt;a&gt; element’s onClick handler.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fvitejs-vite-tenbjt%3Fembed%3D1%26file%3Dsrc%252Fcomponent%252FMouse.jsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fvitejs-vite-tenbjt%3Fembed%3D1%26file%3Dsrc%252Fcomponent%252FMouse.jsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fvitejs-vite-tenbjt%2F3470014d0cbc614e9091bdf2d1bd533a&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/00a6cb4aa97ed9fe686e75d893fefc00/href">https://medium.com/media/00a6cb4aa97ed9fe686e75d893fefc00/href</a></iframe><p>There are also a number of positioning properties:</p><p>• clientX and clientY contain the coordinates measured from the top left of the visible part of the page (regardless of the scroll position.) • pageX and pageY contain the coordinates from the top of the page — which may be currently off-screen due to scrolling. • screenX and screenY give the position within the entire screen.</p><h3>References and articles :</h3><ul><li><a href="https://react.dev/learn/responding-to-events">Responding to Events - React</a></li><li><a href="https://the-guild.dev/blog/react-dom-event-handling-system">Getting to know React DOM&#39;s event handling system inside out - The Guild</a></li><li><a href="https://react.dev/reference/react-dom/components/common">Common components (e.g. ) - React</a></li><li><a href="https://react.dev/learn/adding-interactivity">Adding Interactivity - React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db9d96a9f2c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Fundamentals part 7: Array and lists]]></title>
            <link>https://bits-of-code.medium.com/react-fundamentals-part-7-array-and-lists-2013243ab097?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2013243ab097</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 04:06:02 GMT</pubDate>
            <atom:updated>2024-03-17T04:06:02.084Z</atom:updated>
            <content:encoded><![CDATA[<p>If there’s one unchanging thing about web applications, it’s that they have lists. And so as you might expect, most frameworks attempt to make your life easier with a special syntax for lists.</p><p>But with React, elements are just objects, React.createElement() is just a function, and lists are just old plain arrays</p><p>Rendering a list with React involves three steps:</p><ol><li>Create an array of element objects</li><li>Set that array as the children of a container element</li><li>Render the container element</li></ol><p>Let take a look at this react component</p><pre>import * as React from &quot;react&quot;;<br><br>const animals = [&quot;🦇&quot; ,&quot;🐕&quot; ,&quot;🐈&quot; , &quot;🐄&quot;]<br> <br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;ul&gt;<br>        {animals.map((item) =&gt; (<br>          &lt;li&gt;<br>            &lt;div&gt;{item}&lt;/div&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>As you can see we are creating an array of animals ,Simple right but if we try to open our dev tools and check our console we will find a common react list error</p><blockquote><strong>Warning: Each child in a list should have a unique “key” prop.</strong></blockquote><h3>Arrays and key props</h3><p>When React encounters an array of elements with identical type and props, despite <em>looking</em> identical from the outside, it cannot know that they are <em>really</em> identical. It could be that they each have different internal states.</p><p>This becomes a problem when the <em>order</em> of the elements changes. Because all the elements look identical, React can’t reorder the corresponding DOM nodes.</p><p>To demonstrate, this example renders an array of checkbox elements. Try clicking a checkbox and then clicking the “Reverse” button. Notice how nothing happens.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjs8s7%3Fview%3DEditor%2B%252B%2BPreview%26module%3D%252Fsrc%252Findex.js%26hidenavigation%3D1&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fjs8s7&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fjs8s7%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0f95206e27faa33e8f771b90d2426c4/href">https://medium.com/media/f0f95206e27faa33e8f771b90d2426c4/href</a></iframe><p>And when I tried to log what checkboxes is rendering Ihave this particular tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*FeSeHVRYczosmvqT" /></figure><p>We can observe that indeed we have 3 Element of type input that they all have a prop type=”checkbox”, but there is not really something that can distinguish them.</p><p>But while React can’t distinguish between identical elements in an array, you can always give it some help! And that is what the key prop is for. By providing a key, you’re giving React a way to keep track of otherwise identical elements.</p><p>To see this in action, if i try adding unique key props to each of the checkboxes above. (keys can be strings or numbers — the only thing that matters is that they’re unique). Once you’ve added these, when click a checkbox and then click &quot;Reverse&quot;; the checked boxes should now move as expected!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjs8s7%3Fview%3DEditor%2B%252B%2BPreview%26module%3D%252Fsrc%252Findex.js%26hidenavigation%3D1&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fjs8s7&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fjs8s7%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ec605a7635a853215e20a7f4b78a2be/href">https://medium.com/media/8ec605a7635a853215e20a7f4b78a2be/href</a></iframe><blockquote><strong>In our example, we’ve encapsulated the content JSX and ReactDOM.render method call within a reverseAndRender function. After that, we call the function, which will render the content on the UI when the page loads. It’s also worth noting that the reverseAndRender function call has been inserted within the onClick function. So, whenever we click the button, the reverseAndRender function is called, and the updated reversed checkboxes are displayed on the UI.</strong></blockquote><p>But still, it’s not feasible to call the <strong>reverseAndRender</strong> function every time we want to update the UI. So React added the concept of <strong>State</strong>.</p><ul><li><a href="https://react.dev/learn/rendering-lists">Rendering Lists - React</a></li><li><a href="https://epicreact.dev/why-react-needs-a-key-prop/">Why React needs a key prop</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMJaGti42c5c%3Fstart%3D1%26feature%3Doembed%26start%3D1&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMJaGti42c5c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMJaGti42c5c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ac2822d98f9ba4a18ac2b688a97383b/href">https://medium.com/media/9ac2822d98f9ba4a18ac2b688a97383b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2013243ab097" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Fundamentals part 6: Components]]></title>
            <link>https://bits-of-code.medium.com/react-fundamentals-part-6-components-90b5eb7da01a?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b5eb7da01a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fundamentals]]></category>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 21:44:37 GMT</pubDate>
            <atom:updated>2024-03-10T21:52:25.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXGyHVc62YPZyU3eo3tFKw.gif" /></figure><p>You frequently want to share code, just like in regular <strong>JavaScript</strong>, which you do by using functions. If you want to distribute <strong>JSX</strong>, you can do so as well. These functions are referred to as “components” in <strong>React</strong> and have some unique properties that’s defined or called props.</p><p>To be more specific, components are functions that tell <strong>React</strong> how to render one type of element. Each function takes a props object, and returns a new element that will be rendered in place of the original.</p><pre>...<br>  &lt;script type=&quot;text/babel&quot;&gt;<br> <br>    function message(props) {<br>    // take it as a habit to dustruct props<br>    const {name,ocupation} = props<br>    <br>      return (<br>        &lt;div&gt;<br>          {greeting}, {subject}<br>        &lt;/div&gt;<br>      )<br>    }<br>    const props = { name:&quot;Mayssa&quot;, ocupation:&quot;best linguist researher&quot; }<br>    const customCompnent = message(props)<br>    const element = &lt;div&gt;{customCompnent}&lt;/div&gt;<br>   <br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;))<br>  &lt;/script&gt;<br>...</pre><p>So what type of props can a component receive?</p><p>Like <strong>HTML</strong> elements, they can certainly receive strings and numbers. Custom components can also receive objects, arrays, functions — or even other elements!</p><p>If we want to write JavaScript inside of <strong>JSX</strong> we need to wrap it with curly braces {} .we call that Interpolation</p><p>Taking template literals as an example:</p><pre>const name = &quot;Mayssa&quot; <br>const message =`Hello I&#39;m ${name}`</pre><blockquote>Anything inside `` will be considered in string context but if we wrap it by ${} we can write JavaScript inside it and that’s the JavaScript context . that’s literally Interpolation in action .</blockquote><p>Same thing inside <strong>JSX</strong> but we just ditch the $ and use curly braces, and Babel will understand that we are writing JavaScript there.</p><blockquote><strong>Bear in mind that you can’t do statements inside curly braces as babel can’t interpret them so the best way to do it is to wrap it inside a function</strong></blockquote><blockquote><strong>Expression: Something that evaluates to a value. Example: (1 + 5) / 2 Statement: A line of code that does something. Example: <em>if something does something</em></strong></blockquote><blockquote><strong><em>OPTIONAL</em></strong><em> </em>🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓🎓</blockquote><blockquote><strong>For an explanation of the important differences in composability (chainability) of expressions vs statements, my favorite reference is John Backus’s Turing award paper, </strong><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.130.4539&amp;rep=rep1&amp;type=pdf"><strong><em>Can programming be liberated from the von Neumann style?</em></strong></a><strong>.</strong></blockquote><blockquote><strong>Imperative languages (C, Java, etc.) emphasize statements for program structure and have expressions as an afterthought. Expressions are prioritized in functional languages.</strong></blockquote><blockquote><strong>Because pure functional languages have such powerful expressions, statements can be omitted entirely.</strong></blockquote><pre>...<br>  &lt;script type=&quot;text/babel&quot;&gt;<br> <br>    const condition =true<br>    const element = &lt;div&gt;<br>    {  <br>    // this is wrong  ⛔ ⛔ ⛔ ⛔ ⛔ ⛔ ⛔ <br>    if(condition){console.log(&quot;this will throw an error&quot;)}<br>    }<br>    &lt;/div&gt;<br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;))<br>  &lt;/script&gt;<br>...</pre><p>But you can use ternary operator<em> because, like you thought, it returns an </em><strong><em>expression</em></strong></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">Conditional (ternary) operator - JavaScript | MDN</a></p><pre>...<br>  &lt;script type=&quot;text/babel&quot;&gt;<br> <br>    const condition =true<br>    const element = (<br>      &lt;div&gt;<br>        {<br>        condition<br>          ? &quot;I&#39;ll be rendered hoooray&quot;<br>          : &quot;I&#39;ll will not be rendered&quot;<br>        }<br>      &lt;/div&gt;<br>    );<br>    <br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;))<br>  &lt;/script&gt;<br>...</pre><p>Now let’s return to our initial code</p><pre>...<br>  &lt;script type=&quot;text/babel&quot;&gt;<br> <br>    function message(props) {<br>    // take it as a habit to dustruct props<br>    const {name,ocupation,children} = props<br>    <br>      return (<br>        &lt;div&gt;<br>          {name}, {ocupation} {children}<br>        &lt;/div&gt;<br>      )<br>    }<br>    const props = { name:&quot;Mayssa&quot;, ocupation:&quot;best linguist researher&quot;, children:&quot;Im here&quot; }<br>    const customCompnent = message(props)<br>    const element = &lt;div&gt;{customCompnent}&lt;/div&gt;<br>   <br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;))<br>  &lt;/script&gt;<br>...</pre><p>Remember <strong>React.createElement()</strong>:</p><pre>React.createElement(<br>  type,<br>  {...props},<br>  [...children]<br>)</pre><p>As we said, the type argument for React.createElement() can accept various things, one of which is a <strong>React Element</strong> .</p><p>In our case, we want to create a <strong>React Element</strong> representing the message function.</p><pre>const messageElement = React.createElement(message,props);</pre><p>That will work just fine as <strong>react</strong> instead of creating a <strong>DOM</strong> node. It creates an element that is saved in memory and that will call our message function when we render it on the page.</p><p>If you can recall we can convert <strong>React.createElement()</strong> to <strong>JSX</strong>. Then our code will look something like this:</p><pre>...<br>  &lt;script type=&quot;text/babel&quot;&gt;<br> <br>    function message(props) {<br>    // take it as a habit to dustruct props<br>    const {name,ocupation,children} = props<br>    <br>      return (<br>        &lt;div&gt;<br>          {name}, {ocupation} {children}<br>        &lt;/div&gt;<br>      )<br>    }<br>    <br>    const props = { name:&quot;Mayssa&quot;, ocupation:&quot;best linguist researher&quot; }<br>   <br>    const element = (<br>      &lt;div&gt;<br>        &lt;message name=&quot;Mayssa&quot; ocupation=&quot;best linguist researher&quot;&gt;<br>          Hey I&#39;m here<br>        &lt;/message&gt;<br>      &lt;/div&gt;<br>    );     <br>    <br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;))<br>  &lt;/script&gt;<br>...</pre><blockquote><strong>Babel compiler will not recognize &lt;message&gt;&lt;/message&gt; as a React Element. Instead, it will try to find it as a HTML Tags without a result so it will throw an error.</strong></blockquote><p>If you want to learn more about <strong>HTML</strong> <strong>tags</strong> :</p><p><a href="https://maissen.gitbook.io/maissen-grimoire/html-grimoire/html-cheat-sheet">HTML Cheat Sheet | Maissen&#39;s Grimoire</a></p><p>So we need to let <strong>Babel</strong> know that’s a React Element, and for that, all our React component’s names will need to start with <strong>Uppercase</strong> letter.</p><pre>...<br>  &lt;script type=&quot;text/babel&quot;&gt;<br> <br>    function message(props) {<br>    // take it as a habit to dustruct props<br>    const {name,ocupation,children} = props<br>    <br>      return (<br>        &lt;div&gt;<br>          {name}, {ocupation} {children}<br>        &lt;/div&gt;<br>      )<br>    }<br>    <br>   <br>    const element = (<br>      &lt;div&gt;<br>        &lt;Message name=&quot;Mayssa&quot; ocupation=&quot;best linguist researher&quot;&gt;<br>          Hey I&#39;m here<br>        &lt;/Message&gt;<br>      &lt;/div&gt;<br>    );   <br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;))<br>  &lt;/script&gt;<br>...</pre><p>We can even nest those element inside each others:</p><pre>...<br>  &lt;script type=&quot;text/babel&quot;&gt;<br> <br>    function message(props) {<br>    // take it as a habit to dustruct props<br>    const {name,ocupation,children} = props<br>    <br>      return (<br>        &lt;div&gt;<br>          {name}, {ocupation} {children}<br>        &lt;/div&gt;<br>      )<br>    }<br>    <br>    const props = { name:&quot;Mayssa&quot;, ocupation:&quot;best linguist researher&quot; }<br>   <br>   const element = (<br>      &lt;div&gt;<br>        &lt;Message name=&quot;Mayssa&quot; ocupation=&quot;best linguist researher&quot;&gt;<br>          Hey I&#39;m here<br>        &lt;/Message&gt;<br>        &lt;Message name=&quot;Maissen&quot; ocupation=&quot;Suikoden Guru&quot;&gt;<br>          &lt;Message name=&quot;Maissen child&quot; ocupation=&quot;Suikoden hater&quot;&gt;<br>            Hey I&#39;m here<br>          &lt;/Message&gt;<br>        &lt;/Message&gt;<br>      &lt;/div&gt;<br>    );<br>    <br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;))<br>  &lt;/script&gt;<br>...</pre><blockquote><strong><em>From here on, i’ll will be dealing with JSX in the next chapters as it’s easier to write and is more readable especially if we have a complex tree of components.</em></strong></blockquote><blockquote><strong><em>But always bear in mind that anything that we will do with JSX we can do with React raw APIs.</em></strong></blockquote><h3>Conditional Rendering</h3><p>You can decide to conditionally evaluate one JSX expression over another using different techniques.</p><h3>if-statement</h3><p>You can use the <em>if…else statement</em>.</p><pre>const formatName =<br>  ({ firstName, lastName }: Person) =&gt; `${firstName} ${lastName}`;<br>  <br>interface Person {<br>  firstName: string;<br>  lastName: string;<br>}<br>  <br>interface HelloWorldProps {<br>  person?: Person;<br>}<br>  <br>const HelloWorld = (props: HelloWorldProps) =&gt; {<br>  if (props.person) {<br>    return &lt;div&gt;Hello {formatName(props.person)}&lt;/div&gt;;<br>  } else {<br>    return &lt;div&gt;Hello World&lt;/div&gt;;<br>  }<br>};</pre><h3>Logical operator &amp;&amp;</h3><p><em>In some cases, rather than using the if</em> keyword , it is more convenient and more concise to use an on-the-fly condition (Inline If) with the &amp;&amp; operator.</p><pre>function Mailbox(props) {<br>  const unreadMessages = props.unreadMessages;<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Hello!&lt;/h1&gt;<br>      {unreadMessages.length &gt; 0 &amp;&amp;<br>        &lt;h2&gt;<br>          You have {unreadMessages.length} unread messages.<br>        &lt;/h2&gt;<br>      }<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Conditional ternary operator (… ? … : …)</h3><pre>function Mailbox(props) {<br>  const unreadMessages = props.unreadMessages;<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Hello!&lt;/h1&gt;<br>      {unreadMessages.length === 0 ? (<br>        &lt;h2&gt;<br>          Sorry no new messages :(<br>        &lt;/h2&gt;) : (<br>        &lt;h2&gt;<br>          You have {unreadMessages.length} unread messages.<br>        &lt;/h2&gt;<br>        )<br>      }<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>React Fragments</h3><p><a href="https://legacy.reactjs.org/docs/fragments.html">Fragments - React</a></p><p>When using <strong>React</strong>, it’s a common pattern to return multiple elements by wrapping them with a container element like <strong>div</strong>. This works fine, but by doing so, we’re adding an extra node to the <strong>DOM</strong>. As your app grows, these extra nodes contribute to slow performance. Below is an example without fragments:</p><pre>const Paper = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Header /&gt;<br>      &lt;Main /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;Layout&gt;<br>      &lt;Paper /&gt;<br>      &lt;Sidebar /&gt;<br>    &lt;/Layout&gt;<br>  );<br>};</pre><p>As you see in the dashboard component, we wrap the child elements with a <strong>div</strong> and then call the <strong>Paper</strong> component in the <strong>Home</strong> component. Now, let’s see what it looks like in the browser.</p><pre>&lt;Layout&gt;<br>    &lt;div&gt;<br>        &lt;Header /&gt;<br>        &lt;Main /&gt;<br>    &lt;/div&gt;<br>    &lt;Sidebar /&gt;<br>&lt;/Layout&gt;</pre><p>As you can see in the example, we have an unused div that doesn’t contribute to anything in the layout. This is redundant.</p><h3>How to use Fragments?</h3><p>To solve this problem, Fragments were introduced in <strong>React</strong>. Fragments are used to group a list of children without adding extra nodes to the <strong>DOM</strong>. Let’s look at an example where we use Fragments:</p><pre>const Paper = () =&gt; {<br>  return (<br>    &lt;React.Fragment&gt;<br>      &lt;Header /&gt;<br>      &lt;Main /&gt;<br>    &lt;/React.Fragment&gt;<br>  );<br>};<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;React.Fragment&gt;<br>      &lt;Paper /&gt;<br>      &lt;Sidebar /&gt;<br>    &lt;/React.Fragment&gt;<br>  );<br>};</pre><p>Now, if we look at the browser we’ll see that no additional elements have been added to the <strong>DOM</strong>.</p><pre>&lt;Layout&gt;<br>    &lt;Header/&gt;<br>    &lt;Main/&gt;<br>    &lt;Sidebar/&gt;<br>&lt;Layout&gt;</pre><h3>Syntax</h3><p>Fragments can be used using two types of syntax. The first one is using <strong>React.Fragment</strong> which we’ve used multiple times above. The other one is a new shorter syntax, using empty brackets, that does the same thing.</p><pre>// Using React.Fragment tags  that support Keys or attributes<br>return (<br>  &lt;React.Fragment&gt;<br>    &lt;Paper /&gt;<br>    &lt;Sidebar /&gt;<br>  &lt;/React.Fragment&gt;<br>);<br><br>// Using empty brackets<br>return (<br>  &lt;&gt;<br>    &lt;Paper /&gt;<br>    &lt;Sidebar /&gt;<br>  &lt;/&gt;<br>);</pre><p>Both of these types of syntax work the same. Although, the newer syntax doesn’t support keys or attributes,.</p><h3>References and articles:</h3><ul><li><a href="https://react.dev/learn/your-first-component">Your First Component - React</a></li><li><a href="https://react.dev/learn/conditional-rendering#conditionally-assigning-jsx-to-a-variable">Conditional Rendering - React</a></li><li><a href="https://cheatsheets.shecodes.io/cheatsheets/react/components">Coding Workshops for Women</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FekIDdZE7YjM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DekIDdZE7YjM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FekIDdZE7YjM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/484674efb181e369dd469ef603a8c052/href">https://medium.com/media/484674efb181e369dd469ef603a8c052/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b5eb7da01a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Fundamentals part 5: Styles]]></title>
            <link>https://bits-of-code.medium.com/react-fundamentals-part-5-styles-0d7d1a8b47c3?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d7d1a8b47c3</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[style]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 15:31:50 GMT</pubDate>
            <atom:updated>2024-02-18T15:31:50.000Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://legacy.reactjs.org/docs/faq-styling.html">Styling and CSS - React</a></p><p>Styling a React element is as simple as passing in className and/or style props.</p><p>But <em>which one should you use?</em></p><p>Actually, <em>either is fine</em>. There are times you can’t beat the convenience of adding a short style prop, and there are times when you’ll use className to access the extra power provided by CSS.</p><h4>Limitations of style prop</h4><p>If you want to use selectors, including pseudo-selectors like :hover, then you’ll need to use className.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>    /* just some indicative styling */<br>    &lt;style&gt;<br>      .blue-border {<br>        border: 3px solid blue;<br>      }<br><br>      .blue-border:hover {<br>        border-style: dotted;<br>      }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;script src=&quot;https://unpkg.com/react@17.0.0/umd/react.development.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://unpkg.com/react-dom@17.0.0/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://unpkg.com/@babel/standalone@7.12.4/babel.js&quot;&gt;&lt;/script&gt;<br>    &lt;script type=&quot;text/babel&quot;&gt;<br>      let createElement = React.createElement;<br><br>      const child = createElement(&#39;div&#39;, {<br>        // The `style` prop accepts an object of styles<br>        style: {<br>          width: &#39;100px&#39;,<br>          height: &#39;100px&#39;,<br>          backgroundColor: &#39;aqua&#39;,<br>          padding: &#39;10px&#39;,<br>        },<br>      });<br><br>      const container = createElement(<br>        &#39;div&#39;,<br>        {<br>          // The `className` prop set&#39;s the element&#39;s CSS class.<br>          // The `blue-border` class is defined in styles.css.<br>          className: &#39;blue-border&#39;,<br>        },<br><br>        // The remaining arguments list the element&#39;s children<br>        child,<br>        child<br>      );<br><br>      ReactDOM.render(container, document.getElementById(&#39;root&#39;));<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>And in JSX</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Document&lt;/title&gt;<br>    /* just some indicative styling */<br>    &lt;style&gt;<br>      .blue-border {<br>        border: 3px solid blue;<br>      }<br><br>      .blue-border:hover {<br>        border-style: dotted;<br>      }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;script src=&quot;https://unpkg.com/react@17.0.0/umd/react.development.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://unpkg.com/react-dom@17.0.0/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://unpkg.com/@babel/standalone@7.12.4/babel.js&quot;&gt;&lt;/script&gt;<br>    &lt;script type=&quot;text/babel&quot;&gt;<br>    <br>      const child = &lt;div style={{ width: &#39;100px&#39;, height: &#39;100px&#39;, backgroundColor: &#39;aqua&#39;, padding: &#39;10px&#39; }}&gt;&lt;/div&gt;;<br>      const Container = (<br>        &lt;div className=&quot;blue-border&quot;&gt;<br>          {child}<br>          {child}<br>        &lt;/div&gt;<br>      );<br><br>      ReactDOM.render(Container, document.getElementById(&#39;root&#39;));<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>References and articles:</h3><ul><li><a href="https://blog.yipl.com.np/demystifying-react-styling-approaches-433b84d20337">Demystifying React Styling Approaches</a></li><li><a href="https://www.taniarascia.com/overview-of-css-concepts/">A Complete Guide to CSS Concepts and Fundamentals</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FouncVBiye_M%3Fstart%3D141%26feature%3Doembed%26start%3D141&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DouncVBiye_M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FouncVBiye_M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3dda51fbdf168b10f8c829887d517c5/href">https://medium.com/media/c3dda51fbdf168b10f8c829887d517c5/href</a></iframe><figure><a href="https://www.buymeacoffee.com/elmay"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*bk_C8Um34KavCkO2yzMCZg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d7d1a8b47c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Fundamentals part 3: JSX]]></title>
            <link>https://bits-of-code.medium.com/react-fundamentals-part-3-jsx-94558fa653fa?source=rss-343de517d8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/94558fa653fa</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Maissen Ayed]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 09:02:05 GMT</pubDate>
            <atom:updated>2024-02-10T09:02:05.644Z</atom:updated>
            <content:encoded><![CDATA[<p>Writing our code with <strong>React.createElement()</strong> and <strong>reactDOM.render()</strong>, it’s a little bit verbose and not that readable.</p><p>The good thing the react team thought about that too and created an HTML-like syntactic suger on top of the raw React Api’s called JSX</p><h3>JSX rewrites your JavaScript files</h3><p>JSX is just a tool that converts files like this:</p><pre>const element =<br>  &lt;div id=&quot;container&quot;&gt;<br>    Hello, world!<br>  &lt;/div&gt;</pre><p>into files like this:</p><pre>const element =<br>  React.createElement(<br>    &#39;div&#39;,<br>    {id:&#39;container&#39;},<br>    &quot;Hello, world!&quot;<br>  )</pre><h3>Why use JSX?</h3><p>To use JSX with reasonable performance, you’d need a build process, which would entail (at a minimum) understanding installing node.js, create-react-app, or babel. While this is usually acceptable, there are times when you’d rather avoid the overhead.</p><p>Learning all of this just to avoid typing <strong>createElement()</strong> a few times doesn’t make much sense if you’re just getting started. However, there will come a point when your apps will be large enough that tooling will be a worthwhile investment. And once you’ve arrived at this point, JSX is a fantastic tool to have.</p><ul><li>Large-element definitions are simplified.</li><li>It provides visual cues and assists editors with syntax highlighting.</li><li>It assists React in producing more useful error and warning messages</li></ul><blockquote>Because JSX is not actually JavaScript, you have to convert it using something called a code compiler. <a href="https://babeljs.io/">Babel</a> is one such tool.</blockquote><blockquote>Pro tip: If you’d like to see how JSX gets compiled to JavaScript, <a href="https://babeljs.io/repl#?builtIns=App&amp;code_lz=MYewdgzgLgBArgSxgXhgHgCYIG4D40QAOAhmLgBICmANtSGgPRGm7rNkDqIATtRo-3wMseAFBA&amp;presets=react&amp;prettier=true">check out the online babel REPL here</a>.</blockquote><blockquote>Because JSX is not actually JavaScript, it must be converted using a code compiler. One such tool is Babel.</blockquote><blockquote>If you want to see how JSX is compiled to JavaScript, use the <a href="https://babeljs.io/repl#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&amp;build=&amp;builtIns=App&amp;corejs=3.6&amp;spec=false&amp;loose=false&amp;code_lz=MYewdgzgLgBArgSxgXhgHgCYIG4D40QAOAhmLgBICmANtSGgPRGm7rNkDqIATtRo-3wMseAFBA&amp;debug=false&amp;forceAllTransforms=false&amp;shippedProposals=false&amp;circleciRepo=&amp;evaluate=false&amp;fileSize=false&amp;timeTravel=false&amp;sourceType=module&amp;lineWrap=true&amp;presets=react&amp;prettier=true&amp;targets=&amp;version=7.16.12&amp;externalPlugins=&amp;assumptions=%7B%7D">online babel REPL.</a></blockquote><p>So let’s convert our code to JSX. First of all, like react and reactDOM, we will add babel script from unpkg</p><pre> ...<br>   &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;https://unpkg.com/react@18.0.0/umd/react.development.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://unpkg.com/react-dom@18.0.0/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://unpkg.com/@babel/standalone@7.12.4/babel.js&quot;&gt;&lt;/script&gt;<br>    &lt;script type=&quot;module&quot;&gt;<br>    <br>    const element = React.createElement(&#39;div&#39;, {<br>      className: &#39;container&#39;,<br>      children: &#39;Hello World&#39;,<br>    })<br><br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;));<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>...</pre><p>Then let’s try to change React. createElement() to JSX</p><pre>...<br>&lt;body&gt;<br>  &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;script src=&quot;https://unpkg.com/react@18.0.0/umd/react.development.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;https://unpkg.com/react-dom@18.0.0/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;https://unpkg.com/@babel/standalone@7.12.4/babel.js&quot;&gt;&lt;/script&gt;<br>  &lt;script type=&quot;text/babel&quot;&gt;<br>    // 🔥 &quot;type=&quot;text/bable&quot; to indicate that this code need to be compiled by babel<br>    <br>    // const element = React.createElement(&#39;div&#39;, { className = &#39;container&#39; }); <br>    <br>                                          👇<br>    <br>    const element = &lt;div className=&quot;container&quot;&gt;&lt;/div&gt;<br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;))<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>...</pre><blockquote>You may have noticed that I changed the type of our JavaScript from module to text/babel and that’s to indicate to the browser not to evaluate the script . However, babel will control the compiling for that script</blockquote><p>Easy right? How about children?</p><pre>...<br>&lt;body&gt;<br>  &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;script src=&quot;https://unpkg.com/react@18.0.0/umd/react.development.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;https://unpkg.com/react-dom@18.0.0/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;https://unpkg.com/@babel/standalone@7.12.4/babel.js&quot;&gt;&lt;/script&gt;<br>  &lt;script type=&quot;text/babel&quot;&gt;<br>  // 🔥  &quot;type=&quot;text/bable&quot; to indicate that this code need to be compiled by babel<br>  <br>    // const element = React.createElement(&#39;div&#39;, { className = &#39;container&#39; }, [<br>    //  React.createElement(&#39;div&#39;, { className = &#39;container&#39; }, &quot;I&#39;m the first child&quot;),<br>    //  React.createElement(&#39;div&#39;, { className = &#39;container&#39; }, &quot;I&#39;m the first child&quot;),<br>    // ]); <br>                                    👇 <br><br>    const element = (<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;div className=&quot;firstChild&quot;&gt;I&#39;m the first child&lt;/div&gt;<br>        &lt;div className=&quot;secondChild&quot;&gt;I&#39;m the second child&lt;/div&gt;<br>      &lt;/div&gt;<br>      );<br>    ReactDOM.render(element, document.getElementById(&#39;root&#39;));<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>...</pre><p>JSX appears to be HTML, but it is transformed into plain JavaScript objects under the hood by babel.</p><p>You can’t return two objects from a function unless they’re wrapped in an array. This explains why you can’t return two JSX tags without first wrapping them in another tag or fragment.</p><h3>References and articles:</h3><ul><li><a href="https://react.dev/learn/writing-markup-with-jsx">Writing Markup with JSX - React</a></li><li><a href="https://react.dev/learn/javascript-in-jsx-with-curly-braces">JavaScript in JSX with Curly Braces - React</a></li><li><a href="https://reactjs.org/docs/introducing-jsx.html">Introducing JSX - React</a></li><li><a href="https://reactjs.org/docs/jsx-in-depth.html">JSX In Depth - React</a></li><li><a href="https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html">Introducing the New JSX Transform - React Blog</a></li><li><a href="https://www.frontendcheatsheets.com/cheatsheets/react/jsx">Coding Workshops for Women</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHwNArS3f1Ss%3Flist%3DPLNqp92_EXZBKa1U7JbgUwBnDk3XzYDvXe&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHwNArS3f1Ss&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHwNArS3f1Ss%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/86496d3e01ac279b0041e506a1f0d289/href">https://medium.com/media/86496d3e01ac279b0041e506a1f0d289/href</a></iframe><figure><a href="https://www.buymeacoffee.com/elmay"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*bk_C8Um34KavCkO2yzMCZg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94558fa653fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>