<?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 Ali Husen on Medium]]></title>
        <description><![CDATA[Stories by Ali Husen on Medium]]></description>
        <link>https://medium.com/@aliWhosane?source=rss-67475f8e93bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rMGaUk6FQ9aN8LKW.</url>
            <title>Stories by Ali Husen on Medium</title>
            <link>https://medium.com/@aliWhosane?source=rss-67475f8e93bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 14:21:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aliWhosane/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[Tesla in 2026: The “Valuation Void” Explained]]></title>
            <link>https://medium.com/@aliWhosane/tesla-in-2026-the-valuation-void-explained-5ec858834190?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ec858834190</guid>
            <category><![CDATA[tesla]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[elon-musk]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 03:35:42 GMT</pubDate>
            <atom:updated>2026-02-03T03:35:42.873Z</atom:updated>
            <content:encoded><![CDATA[<p>Is Tesla a struggling car company or a dominant AI monopoly? The final data from 2025 suggests it is both — and that is why the stock remains the most contentious battleground on Wall Street.</p><p>I am a fan have been wondering if I should invest and so I did a deep dive into the state of Tesla as we enter February 2026, and the numbers tell a story of three distinct businesses moving in different directions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSzM_zw1_-Wjc_twwmKtaw.jpeg" /></figure><h3>📉 The Auto Business has hit a wall.</h3><p>For the first time, Tesla’s annual deliveries dropped significantly (-9% in 2025), settling at <strong>1.64 million</strong> vehicles. Meanwhile, <strong>BYD</strong> has effectively ended the era of uncontested growth, delivering <strong>4.6 million</strong> total vehicles in 2025 (including 2.26 million BEVs). Tesla is no longer the people’s champion or the undisputed volume king.</p><h3>🔋 The Energy Business is the new profit engine.</h3><p>While cars struggled, Tesla Energy became a juggernaut. Energy storage deployments hit <strong>46.7 GWh</strong> for the year, with the segment generating over <strong>$1.1B in profit</strong> in Q4 alone. This is no longer a side project; it is utility-scale infrastructure printing cash at nearly 30% margins. Honestly this is the most overlooked part of Tesla. This alone as an individual company would be valued at <strong>$120 Billion.</strong></p><h3>🤖 The AI Bet (Robotaxi &amp; Optimus) is where the value lives.</h3><p>Here is the reality check on the “AI Company” pivot:</p><ul><li><strong>Autonomy:</strong> Tesla officially disclosed <strong>1.1 million</strong> FSD subscribers/owners in Jan 2026. However, <strong>Waymo</strong> (now valued at $126B) is already doing over <strong>450,000 paid rides per week</strong> and has surpassed 150 million driverless miles. I can’t compare them with Tesla’s paid rides cause they are hardly doing any without safety monitors.</li><li><strong>Robotics:</strong> While Optimus remains in pilot phases, Chinese competitor <strong>Unitree Robotics</strong> confirmed it shipped over <strong>5,500</strong> humanoid robots to customers in 2025. The hardware race is tighter than many realize, US firm <strong>Figure AI</strong> successfully deployed its <strong>Figure 02</strong> robot at <strong>BMW’s Spartanburg plant</strong> in 2025. The robots logged over 1,250 hours of useful work, inserting sheet metal parts into chassis fixtures.</li></ul><h3>The Verdict?</h3><p>At <strong>~$421/share</strong>, it has been long since the market has priced Tesla on the cars it sells or any kind of reality. With a market cap holding steady at <strong>$1.3 trillion</strong> despite a delivery slump, investors are paying for the “Physical AI” future. With Waymo scaling and Figure AI hitting massive valuations, Tesla is in a losing dogfight to prove its software can dominate the physical world.</p><p>Many have bet against Musk in past and lost, will we see him pull this one off too?</p><p>#Tesla #EV #ArtificialIntelligence #Robotaxi #TechTrends #Valuation</p><p>P.S. — I am not anti-tesla and this is just an honest article about what I think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ec858834190" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Error Handling for React in 2025: Best Practices and Examples]]></title>
            <link>https://javascript.plainenglish.io/mastering-error-handling-for-react-in-2025-best-practices-and-examples-781180b5d023?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/781180b5d023</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 17:47:38 GMT</pubDate>
            <atom:updated>2024-12-09T17:47:38.470Z</atom:updated>
            <content:encoded><![CDATA[<p>Error handling is an essential aspect of any React application, ensuring a smooth user experience even when things go wrong. This article will guide you through handling errors in various types of components, such as forms, server data fetching, with practical examples so you are ready to tame them in 2025. First let’s try and understand what good error handling provides to the Application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WOzO8XvmProOtvgM" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Is Error Handling Important?</h3><p>Proper error handling helps:</p><ul><li>Inform users about issues without breaking the app.</li><li>Debug applications by capturing detailed error information.</li><li>Improve the overall user experience.</li></ul><h3>Types of Errors in React Applications</h3><p>Okay so now we know why we need it, let’s quickly list down various types of errors and then we will deep dive into how we handle them in detail.</p><ol><li><strong>UI Rendering Errors:</strong> Problems within the React components themselves.</li><li><strong>User Input Errors:</strong> Mistakes users make, like entering invalid data into forms.</li><li><strong>Server Errors:</strong> Issues while fetching or sending data to a server.</li></ol><h3>Error Boundaries for UI Rendering Errors</h3><p>Error boundaries are React components designed to catch JavaScript errors in child components. They prevent the entire app from crashing due to a single faulty component.</p><h3>Code Example: Error Boundary</h3><pre>import React from &#39;react&#39;;<br><br>class ErrorBoundary extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { hasError: false };<br>  }<br>  static getDerivedStateFromError(error) {<br>    return { hasError: true };<br>  }<br>  componentDidCatch(error, errorInfo) {<br>    console.error(&quot;Error captured:&quot;, error, errorInfo);<br>  }<br>  render() {<br>    if (this.state.hasError) {<br>      return &lt;h1&gt;Something went wrong.&lt;/h1&gt;;<br>    }<br>    return this.props.children;<br>  }<br>}<br>export default ErrorBoundary;</pre><h3>Usage</h3><p>Wrap your potentially error-prone components with the ErrorBoundary. I always prefer having one that encompasses the entire application as a fail safe.</p><pre>&lt;ErrorBoundary&gt;<br>  &lt;MyComponent /&gt;<br>&lt;/ErrorBoundary&gt;</pre><h3>Handling Errors in Forms</h3><p>Forms are a common source of user input errors. Using libraries like react-hook-form or Formik can simplify form validation and error handling.</p><h3>Code Example: Validating a Login Form</h3><pre>import React from &#39;react&#39;;<br>import { useForm } from &#39;react-hook-form&#39;;<br><br>function LoginForm() {<br>  const { register, handleSubmit, formState: { errors } } = useForm();<br>  const onSubmit = (data) =&gt; {<br>    console.log(&quot;Form data submitted:&quot;, data);<br>  };<br>  return (<br>    &lt;form onSubmit={handleSubmit(onSubmit)}&gt;<br>      &lt;div&gt;<br>        &lt;label&gt;Email:&lt;/label&gt;<br>        &lt;input<br>          {...register(&quot;email&quot;, { required: &quot;Email is required&quot; })}<br>        /&gt;<br>        {errors.email &amp;&amp; &lt;span&gt;{errors.email.message}&lt;/span&gt;}<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;label&gt;Password:&lt;/label&gt;<br>        &lt;input<br>          type=&quot;password&quot;<br>          {...register(&quot;password&quot;, { required: &quot;Password is required&quot; })}<br>        /&gt;<br>        {errors.password &amp;&amp; &lt;span&gt;{errors.password.message}&lt;/span&gt;}<br>      &lt;/div&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}<br>export default LoginForm;</pre><p><strong>Best Practice:</strong> Always provide clear error messages to guide users in correcting their input.</p><h3>Handling Errors in Data Fetching</h3><p>When fetching data from a server, errors like network issues or invalid responses can occur. Libraries like axios or React&#39;s fetch can help handle these errors effectively.</p><h3>Code Example: Fetching Data with Error Handling</h3><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>function DataFetcher() {<br>  const [data, setData] = useState(null);<br>  const [error, setError] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  useEffect(() =&gt; {<br>    async function fetchData() {<br>      try {<br>        const response = await fetch(&#39;https://api.example.com/data&#39;);<br>        if (!response.ok) {<br>          throw new Error(&#39;Failed to fetch data&#39;);<br>        }<br>        const result = await response.json();<br>        setData(result);<br>      } catch (err) {<br>        setError(err.message);<br>      } finally {<br>        setLoading(false);<br>      }<br>    }<br>    fetchData();<br>  }, []);<br>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error: {error}&lt;/p&gt;;<br>  return &lt;div&gt;Data: {JSON.stringify(data)}&lt;/div&gt;;<br>}<br>export default DataFetcher;</pre><p><strong>Best Practice:</strong> Use a loading state to indicate that data is being fetched, and handle server errors gracefully by showing a fallback UI or message.</p><h3>Centralized Error Handling</h3><p>For larger applications, consider centralizing error handling using tools like React Query or a global error boundary.</p><h3>Example: Using React Query</h3><pre>import { useQuery } from &#39;react-query&#39;;<br><br>function Products() {<br>  const { data, error, isLoading } = useQuery(&#39;products&#39;, fetchProducts);<br>  if (isLoading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error: {error.message}&lt;/p&gt;;<br>  return (<br>    &lt;ul&gt;<br>      {data.map(product =&gt; (<br>        &lt;li key={product.id}&gt;{product.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}<br>async function fetchProducts() {<br>  const response = await fetch(&#39;https://api.example.com/products&#39;);<br>  if (!response.ok) {<br>    throw new Error(&#39;Failed to fetch products&#39;);<br>  }<br>  return response.json();<br>}</pre><p><strong>Best Practice:</strong> Centralized error handling ensures consistency and simplifies debugging.</p><h3>General Best Practices for Error Handling in React</h3><p>Let’s sum up all the best practices that we need to follow here as quick reminder of things we should be careful about while implementing Error handling.</p><ol><li><strong>Fail Gracefully:</strong> Always provide fallback UIs or error messages for better user experience.</li><li><strong>Avoid Overloading Users:</strong> Show concise error messages and avoid technical jargon.</li><li><strong>Log Errors:</strong> Use logging tools like Sentry to track and debug errors in production.</li><li><strong>Handle All Error Types:</strong> Address server errors, validation issues, and rendering errors appropriately.</li><li><strong>Test Error Scenarios:</strong> Simulate different error cases during development to ensure robustness.</li></ol><p>Effective error handling in React is about balancing technical accuracy and user experience. By implementing error boundaries, validating user input, handling server errors, and following best practices, you can build resilient and user-friendly applications.</p><p>The examples provided here should serve as a solid foundation for incorporating robust error handling into your React projects you have started working on for 2025.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=781180b5d023" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/mastering-error-handling-for-react-in-2025-best-practices-and-examples-781180b5d023">Mastering Error Handling for React in 2025: Best Practices and Examples</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Reusable Components in React: A Step-by-Step Guide with example]]></title>
            <link>https://javascript.plainenglish.io/building-reusable-components-in-react-a-step-by-step-guide-with-example-0e8eece72271?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e8eece72271</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 14:56:29 GMT</pubDate>
            <atom:updated>2024-11-20T14:56:29.538Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of React, reusability is one of the most important thing for an efficient and maintainable code. Creating reusable components not only saves time but also ensures consistency across your application. In this guide, we’ll explore the principles, best practices, and step-by-step methods to build reusable React components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hEu0uoADdw-tm-Ya" /><figcaption>Photo by <a href="https://unsplash.com/@enginakyurt?utm_source=medium&amp;utm_medium=referral">engin akyurt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why Reusable Components Matter</h3><p>For most developer this is obvious, but I know that a lot of young developers are starting directly from React and for them here is why reusability matters.</p><ul><li><strong>Reduce Redundancy</strong>: Write code once and use it across the application.</li><li><strong>Improve Consistency</strong>: Maintain uniform UI elements throughout the app.</li><li><strong>Boost Productivity</strong>: Save development time by reusing components instead of starting from scratch.</li><li><strong>Enhance Maintainability</strong>: Centralize updates to components, reducing potential bugs.</li></ul><h3>Principles of Reusable Components</h3><p>Now let’s go over the principles to follow when creating reusable components.</p><ol><li><strong>Single Responsibility Principle (SRP):</strong><br>A component should do one thing and do it well. Avoid combining unrelated functionalities.</li><li><strong>Avoid Hardcoding:</strong><br>Use props to make components configurable rather than rigid.</li><li><strong>Composition Over Inheritance:</strong><br>Instead of extending components, compose them using children or higher-order components.</li><li><strong>Styling Flexibility:</strong><br>Provide hooks for customizing styles without overriding internal logic.</li></ol><h3>Steps to Build Reusable Components</h3><h4>Step 1: Identify Common Patterns</h4><p>Start by analyzing your design or codebase to identify repeating UI elements. For instance:</p><ul><li>Buttons</li><li>Input fields</li><li>Cards</li><li>Modal dialogs</li></ul><h4>Step 2: Plan the Component API</h4><p>By API I mean the props your component should accept. Think about the following:</p><ul><li><strong>Functionality</strong>: What actions should the component handle?</li><li><strong>Styling</strong>: How can developers customize its appearance?</li><li><strong>Extensibility</strong>: Should it allow children or additional elements?</li></ul><p>Example: A reusable button might have props like label, onClick, variant, and disabled.</p><h4>Step 3: Code the Component</h4><p>Let’s take an example of a Button component and create a reuseable version of it:</p><pre>import React from &#39;react&#39;;  <br>import PropTypes from &#39;prop-types&#39;;<br><br>const Button = ({ label, onClick, variant, disabled }) =&gt; {  <br>  const className = `button ${variant}`;  <br><br>  return (  <br>    &lt;button  <br>      className={className}  <br>      onClick={onClick}  <br>      disabled={disabled}  <br>    &gt;  <br>      {label}  <br>    &lt;/button&gt;  <br>  );  <br>};  <br><br>Button.propTypes = {  <br>  label: PropTypes.string.isRequired,  <br>  onClick: PropTypes.func.isRequired,  <br>  variant: PropTypes.oneOf([&#39;primary&#39;, &#39;secondary&#39;, &#39;danger&#39;]),  <br>  disabled: PropTypes.bool,  <br>};  <br><br>Button.defaultProps = {  <br>  variant: &#39;primary&#39;,  <br>  disabled: false,  <br>};  <br><br>export default Button;</pre><h4>Step 4: Handle Customization</h4><p>Add props for customization, such as:</p><ul><li><strong>Variants</strong>: Different styles for the component (e.g., primary, secondary).</li><li><strong>Icons</strong>: Allow additional elements like icons inside the button.</li></ul><p>Example with icon support:</p><pre>const Button = ({ label, onClick, variant, disabled, icon }) =&gt; {  <br>  return (  <br>    &lt;button  <br>      className={`button ${variant}`}  <br>      onClick={onClick}  <br>      disabled={disabled}  <br>    &gt;  <br>      {icon &amp;&amp; &lt;span className=&quot;icon&quot;&gt;{icon}&lt;/span&gt;}  <br>      {label}  <br>    &lt;/button&gt;  <br>  );  <br>};</pre><h4>Step 5: Make it Composable</h4><p>Design components to work well together. For instance, a Card component could accept a Header, Body, and Footer.</p><pre>const Card = ({ header, body, footer }) =&gt; {  <br>  return (  <br>    &lt;div className=&quot;card&quot;&gt;  <br>      {header &amp;&amp; &lt;div className=&quot;card-header&quot;&gt;{header}&lt;/div&gt;}  <br>      &lt;div className=&quot;card-body&quot;&gt;{body}&lt;/div&gt;  <br>      {footer &amp;&amp; &lt;div className=&quot;card-footer&quot;&gt;{footer}&lt;/div&gt;}  <br>    &lt;/div&gt;  <br>  );  <br>};</pre><p>Example Usage:</p><pre>&lt;Card  <br>  header={&lt;h2&gt;Card Title&lt;/h2&gt;}  <br>  body={&lt;p&gt;This is the card content.&lt;/p&gt;}  <br>  footer={&lt;button&gt;Read More&lt;/button&gt;}  <br>/&gt;</pre><h3>Best Practices for Reusable Components</h3><ol><li><strong>Document Usage:</strong><br>If you want it to be reusable you better write clear documentation for each component’s props and use cases.</li><li><strong>Use Storybook:</strong><br>Storybook has it’s learning curve but in the long run makes it easy to see your components in isolation and verify their appearance and behavior.</li><li><strong>Avoid Overgeneralization:</strong><br>Start simple. Don’t make a component overly complex in an attempt to handle every scenario.</li><li><strong>Consistent Styling Approach:</strong><br>I am a Tailwind fanboy, but you can use others like CSS-in-JS library, CSS modules, or other utility classes for consistent styling.</li><li><strong>Export Components as a Library:</strong><br>If your project grows, consider exporting reusable components as an NPM package.</li></ol><p>Reusable components are the building blocks of scalable React applications. By following best practices and planning your components thoughtfully, you can create a robust, efficient, and maintainable codebase. Start small, iterate based on project needs, and enjoy the productivity boost that comes with reusable components!</p><p>Have you built reusable components in your React projects? Share your experience in the comments below! 😊</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e8eece72271" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-reusable-components-in-react-a-step-by-step-guide-with-example-0e8eece72271">Building Reusable Components in React: A Step-by-Step Guide with example</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using MobX-State-Tree with React: What, How & some Code Snippets]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/using-mobx-state-tree-with-react-what-how-some-code-snippets-dba5b9806c53?source=rss-67475f8e93bc------2"><img src="https://cdn-images-1.medium.com/max/2600/0*FPA1QGX8CsXE1BEx" width="6024"></a></p><p class="medium-feed-snippet">MobX-State-Tree (MST) is a state management library that combines the reactivity of MobX with a strict, schema-based structure. MST is&#x2026;</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/using-mobx-state-tree-with-react-what-how-some-code-snippets-dba5b9806c53?source=rss-67475f8e93bc------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/using-mobx-state-tree-with-react-what-how-some-code-snippets-dba5b9806c53?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/dba5b9806c53</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 05:38:38 GMT</pubDate>
            <atom:updated>2024-11-04T14:58:56.773Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding Concurrent Rendering in React]]></title>
            <link>https://javascript.plainenglish.io/understanding-concurrent-rendering-in-react-e388ef3e47d2?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e388ef3e47d2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 12:17:07 GMT</pubDate>
            <atom:updated>2024-07-15T12:17:07.259Z</atom:updated>
            <content:encoded><![CDATA[<p>Concurrent Rendering is a feature introduced in React 18 that allows React to prepare multiple versions of the UI simultaneously. This capability makes applications more responsive by allowing React to interrupt the rendering process to work on more urgent updates, such as user interactions or animations. This is a significant improvement over the traditional synchronous rendering, where React would complete one update before starting another, sometimes causing delays and blocking the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXUqxwEN-5Y6wdwFrI1ewg.png" /></figure><h3>How Concurrent Rendering Works</h3><p>Let’s figure out how exactly does Concurrent Rendering works. Essentially it breaks down rendering work into smaller chunks and spreads it over multiple frames. This enables React to handle high-priority updates (like user inputs) without waiting for less critical work to complete. Here’s a high-level overview of how it functions:</p><ol><li>Scheduling: React schedules updates based on their priority. High-priority updates like user interactions are handled immediately, while low-priority updates are delayed until the main thread is free.</li><li>Interruptible Rendering: React can pause work on a lower-priority update to handle a higher-priority one. This prevents the UI from becoming unresponsive.</li><li>Time Slicing: React breaks rendering work into small chunks and spreads them over multiple frames. This keeps the main thread free to handle other tasks.</li><li>Suspense: React Suspense lets you declaratively specify loading states for parts of the UI, enabling a smoother user experience during data fetching.</li></ol><h3>Where to Use Concurrent Rendering</h3><p>You may be wondering what is this drama about. When are we even going to use this? Concurrent Rendering is beneficial in various scenarios, such as:</p><ul><li>Complex User Interfaces: Interfaces with multiple interactive components, like dashboards or real-time data applications.</li><li>Data Fetching: Handling asynchronous data fetching with smooth loading states.</li><li>Animations and Transitions: Keeping animations smooth even when the application is under heavy load.</li><li>Input Handling: Ensuring that user inputs (clicks, typing) are responsive even during intensive rendering tasks.</li></ul><h3>Example: Using Concurrent Rendering for Data Fetching</h3><p>Let’s dive into an example to understand how Concurrent Rendering can be used for data fetching with React Suspense.</p><h3>Step 1: Set Up a Suspense Boundary</h3><p>First, let’s create a Suspense boundary around a component that fetches data. This will allow React to handle the loading state while the data is being fetched.</p><pre>import React, { Suspense } from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import App from &#39;./App&#39;;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;App /&gt;<br>    &lt;/Suspense&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><h3>Step 2: Create a Data Fetching Component</h3><p>Next, create a component that fetches data. We’ll use a simple mock API call for demonstration.</p><pre>// dataFetcher.js<br>export function fetchData() {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(() =&gt; {<br>      resolve({ message: &#39;Hello from the server!&#39; });<br>    }, 2000);<br>  });<br>}<br><br>// DataComponent.js<br>import React from &#39;react&#39;;<br>import { fetchData } from &#39;./dataFetcher&#39;;<br>const resource = fetchData();<br>function DataComponent() {<br>  const data = resource.read();<br>  return &lt;div&gt;{data.message}&lt;/div&gt;;<br>}<br>export default DataComponent;</pre><h3>Step 3: Create a Resource Wrapper</h3><p>To handle the asynchronous nature of data fetching, we’ll create a resource wrapper that Suspense can work with.</p><pre>// resource.js<br>function wrapPromise(promise) {<br>  let status = &#39;pending&#39;;<br>  let result;<br>  let suspender = promise.then(<br>    (r) =&gt; {<br>      status = &#39;success&#39;;<br>      result = r;<br>    },<br>    (e) =&gt; {<br>      status = &#39;error&#39;;<br>      result = e;<br>    }<br>  );<br>  return {<br>    read() {<br>      if (status === &#39;pending&#39;) {<br>        throw suspender;<br>      } else if (status === &#39;error&#39;) {<br>        throw result;<br>      } else if (status === &#39;success&#39;) {<br>        return result;<br>      }<br>    }<br>  };<br>}<br><br>export function fetchData() {<br>  return wrapPromise(<br>    new Promise((resolve) =&gt; {<br>      setTimeout(() =&gt; {<br>        resolve({ message: &#39;Hello from the server!&#39; });<br>      }, 2000);<br>    })<br>  );<br>}</pre><h3>Step 4: Use the Suspense Component in Your App</h3><p>Now, we can use the DataComponent inside our App component, wrapped in a Suspense boundary.</p><pre>// App.js<br>import React from &#39;react&#39;;<br>import DataComponent from &#39;./DataComponent&#39;;<br><br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Concurrent Rendering Example&lt;/h1&gt;<br>      &lt;DataComponent /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><h3>Full Code for Reference</h3><p>Here’s the full code in one place so you can copy and paste it in your project and tweak and test it as per your requirements.</p><pre>// index.js<br>import React, { Suspense } from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import App from &#39;./App&#39;;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;App /&gt;<br>    &lt;/Suspense&gt;<br>  &lt;/React.StrictMode&gt;<br>);<br>// dataFetcher.js<br>function wrapPromise(promise) {<br>  let status = &#39;pending&#39;;<br>  let result;<br>  let suspender = promise.then(<br>    (r) =&gt; {<br>      status = &#39;success&#39;;<br>      result = r;<br>    },<br>    (e) =&gt; {<br>      status = &#39;error&#39;;<br>      result = e;<br>    }<br>  );<br>  return {<br>    read() {<br>      if (status === &#39;pending&#39;) {<br>        throw suspender;<br>      } else if (status === &#39;error&#39;) {<br>        throw result;<br>      } else if (status === &#39;success&#39;) {<br>        return result;<br>      }<br>    }<br>  };<br>}<br>export function fetchData() {<br>  return wrapPromise(<br>    new Promise((resolve) =&gt; {<br>      setTimeout(() =&gt; {<br>        resolve({ message: &#39;Hello from the server!&#39; });<br>      }, 2000);<br>    })<br>  );<br>}<br>// DataComponent.js<br>import React from &#39;react&#39;;<br>import { fetchData } from &#39;./dataFetcher&#39;;<br>const resource = fetchData();<br>function DataComponent() {<br>  const data = resource.read();<br>  return &lt;div&gt;{data.message}&lt;/div&gt;;<br>}<br>export default DataComponent;<br>// App.js<br>import React from &#39;react&#39;;<br>import DataComponent from &#39;./DataComponent&#39;;<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Concurrent Rendering Example&lt;/h1&gt;<br>      &lt;DataComponent /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><h4>I hope this made you think about how you will create your next React Application.</h4><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e388ef3e47d2" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-concurrent-rendering-in-react-e388ef3e47d2">Understanding Concurrent Rendering in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming with React]]></title>
            <link>https://javascript.plainenglish.io/functional-programming-with-react-ef55329cc524?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef55329cc524</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 08:16:56 GMT</pubDate>
            <atom:updated>2024-01-30T08:16:56.790Z</atom:updated>
            <content:encoded><![CDATA[<p>Functional programming has emerged as a powerful paradigm in software development, and its principles are particularly relevant in the context of React. Before we get into how functional programming is implemented in ReactJs let’s look into what ‘Functional Programming’ exactly means.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IIr9YGQUuQ9nxjKyB19cw.png" /><figcaption>image src: Dall-E</figcaption></figure><p>Functional programming (FP) is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming paradigm, which emphasizes changes in state.</p><p>Key principles of functional programming include:</p><ol><li><strong>Immutability</strong>: Avoid changing data in place and instead create new data structures with updated values.</li><li><strong>Pure Functions</strong>: Functions that, given the same inputs, always return the same output and do not cause any side effects.</li><li><strong>First-Class and Higher-Order Functions</strong>: Treating functions as values that can be passed as arguments, returned from other functions, and assigned to variables.</li><li><strong>Declarative Rather Than Imperative</strong>: Describing what the program should accomplish rather than detailing the steps to achieve it.</li></ol><h3>Functional Programming in React</h3><p>React, at its core, embraces functional programming principles, especially with the introduction of hooks. The use of functional components, hooks, and immutable state management aligns well with FP concepts.</p><h3>Immutable State Updates</h3><p>In React, state should be treated as immutable. This means when you want to update the state, you should not modify it directly but instead return a new object that represents the new state.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  const incrementCount = () =&gt; {<br>    setCount(prevCount =&gt; prevCount + 1);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={incrementCount}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Pure Components</h3><p>A pure component is one that always renders the same output for the same state and props. React offers React.memo for creating pure functional components.</p><pre>import React, { memo } from &#39;react&#39;;<br><br>const PureComp = memo(props =&gt; {<br>  // This component will only re-render if props change<br>  return &lt;div&gt;{props.message}&lt;/div&gt;;<br>});</pre><h3>Higher-Order Components</h3><p>A higher-order component (HOC) is a function that takes a component and returns a new component. It’s a pattern that’s derived from React’s compositional nature and is a good example of functional programming.</p><pre>import React from &#39;react&#39;;<br><br>function withLogger(WrappedComponent) {<br>  return function(props) {<br>    console.log(&#39;Props:&#39;, props);<br>    return &lt;WrappedComponent {...props} /&gt;;<br>  };<br>}<br><br>// Usage<br>// const EnhancedComponent = withLogger(OriginalComponent);</pre><h3>Hooks as First-Class Functions</h3><p>Hooks in React, like useState and useEffect, are first-class functions that can be used inside functional components to handle state and side effects in a functional manner.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function ExampleComponent() {<br>  const [data, setData] = useState(null);<br><br>  useEffect(() =&gt; {<br>    fetchData().then(setData);<br>  }, []); // Empty array ensures this runs once, similar to componentDidMount<br><br>  // render logic<br>}</pre><p>Functional programming in React brings several benefits, including cleaner and more predictable code, easier testing, and a more declarative style of programming. Whenever you work with ReactJs ask yourself if your code is adhering to functional programming for the best experience.</p><p>Follow me if you enjoyed my content &amp; <a href="https://bmc.link/aliwhosane">buy me a coffee</a> if you are feeling super generous :)</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef55329cc524" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/functional-programming-with-react-ef55329cc524">Functional Programming with React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Microservices with 5 Famous Design Patterns]]></title>
            <link>https://javascript.plainenglish.io/implementing-microservices-with-5-famous-design-patterns-c14af1745d5b?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c14af1745d5b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 12:16:46 GMT</pubDate>
            <atom:updated>2024-07-01T23:35:52.074Z</atom:updated>
            <content:encoded><![CDATA[<p>Microservices architecture, combined with the power of Node.js, offers a scalable, maintainable, and resilient solution in software development. We will explore the implementation of microservices using Node.js, focusing on five famous design patterns, hope you find it useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkCWf3mZ43yy4NZXiMWrww.png" /><figcaption>Image src: Dall-E</figcaption></figure><p><strong>1. The API Gateway Pattern</strong></p><p>A fundamental pattern in microservices is the API Gateway, which acts as a single entry point for all client requests. In Node.js, the Express.js framework is ideal for building an API Gateway.</p><pre>const express = require(&#39;express&#39;);<br>const httpProxy = require(&#39;express-http-proxy&#39;);<br><br>const userServiceProxy = httpProxy(&#39;http://localhost:3001&#39;);<br>const orderServiceProxy = httpProxy(&#39;http://localhost:3002&#39;);<br><br>const app = express();<br><br>app.get(&#39;/users&#39;, (req, res, next) =&gt; userServiceProxy(req, res, next));<br>app.get(&#39;/orders&#39;, (req, res, next) =&gt; orderServiceProxy(req, res, next));<br><br>app.listen(3000, () =&gt; console.log(&#39;API Gateway running on port 3000&#39;));</pre><p><strong>2. The Service Registry Pattern</strong></p><p>Service Registry involves a database of service instances for dynamic discovery. Node.js can use packages like consul for this purpose.</p><pre>const consul = require(&#39;consul&#39;)();<br><br>consul.agent.service.register({<br>  name: &quot;my_microservice&quot;,<br>  id: &quot;my_microservice_12345&quot;,<br>  address: &#39;localhost&#39;,<br>  port: 3000,<br>}, err =&gt; {<br>  if (err) throw err;<br>  console.log(&#39;Service registered with Consul&#39;);<br>});</pre><p><strong>3. The Circuit Breaker Pattern</strong></p><p>The Circuit Breaker pattern prevents network or service failures from affecting the entire system. In Node.js, opossum is a popular choice for implementing circuit breakers.</p><pre>const circuitBreaker = require(&#39;opossum&#39;);<br><br>function unreliableFunction() {<br>  return new Promise((resolve, reject) =&gt; {<br>    Math.random() &gt; 0.5 ? resolve(&#39;Success&#39;) : reject(new Error(&#39;Failed&#39;));<br>  });<br>}<br><br>const breaker = new circuitBreaker(unreliableFunction);<br>breaker.fallBack(() =&gt; &#39;Fallback response&#39;);<br>breaker.fire();</pre><p><strong>4. The Observer Pattern</strong></p><p>The Observer pattern is used for event-driven architectures. Node.js, with its event-driven nature, integrates well with tools like RabbitMQ for event handling.</p><pre>const amqp = require(&#39;amqplib&#39;);<br><br>async function publishMessage() {<br>  const connection = await amqp.connect(&#39;amqp://localhost&#39;);<br>  const channel = await connection.createChannel();<br>  const queue = &#39;myQueue&#39;;<br><br>  await channel.assertQueue(queue, { durable: false });<br>  channel.sendToQueue(queue, Buffer.from(&#39;Hello World!&#39;));<br><br>  console.log(&quot;Sent &#39;Hello World!&#39;&quot;);<br>}<br><br>publishMessage();</pre><p><strong>5. The Aggregator Pattern</strong></p><p>The Aggregator Pattern creates a composite service that consolidates data from multiple services. Node.js facilitates this pattern using asynchronous operations and Promises.</p><pre>const express = require(&#39;express&#39;);<br>const axios = require(&#39;axios&#39;);<br><br>const app = express();<br><br>app.get(&#39;/aggregate&#39;, async (req, res) =&gt; {<br>  try {<br>    const [userResponse, orderResponse] = await Promise.all([<br>      axios.get(&#39;http://localhost:3001/users&#39;),<br>      axios.get(&#39;http://localhost:3002/orders&#39;)<br>    ]);<br><br>    res.json({ users: userResponse.data, orders: orderResponse.data });<br>  } catch (error) {<br>    res.status(500).send(error.message);<br>  }<br>});<br><br>app.listen(3003, () =&gt; console.log(&#39;Aggregator running on port 3003&#39;));</pre><p>Implementing microservices with Node.js using these five design patterns provides a solid foundation for building scalable and resilient systems. Each pattern addresses specific architectural challenges, enhancing the overall functionality and efficiency of the system.</p><p>Follow me for more content &amp; <a href="https://bmc.link/aliwhosane">buy me a coffee</a> if you are feeling super generous.</p><h3>Further Reading:</h3><p><a href="https://differ.blog/p/where-did-microservices-go-794f4f">Where Did Microservices Go?</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c14af1745d5b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/implementing-microservices-with-5-famous-design-patterns-c14af1745d5b">Implementing Microservices with 5 Famous Design Patterns</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using FlushSync in React]]></title>
            <link>https://javascript.plainenglish.io/using-flushsync-in-react-b719ef8adc56?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b719ef8adc56</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 15:16:01 GMT</pubDate>
            <atom:updated>2024-01-03T15:16:01.446Z</atom:updated>
            <content:encoded><![CDATA[<p>React has a lot of efficient and flexible ways of managing UI updates. One of the less commonly used but crucial features is flushSync. This article delves into what flushSync is, how, and when to use it, and importantly, when not to use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DZE2_Se1KFtLwmq_wxUmA.png" /><figcaption>image credit: Dall-E</figcaption></figure><h3>What is flushSync in React?</h3><p>Introduced in React 18, flushSync is a function that forces React to re-render synchronously within its callback, before continuing with the rest of the JavaScript event loop. This goes against React&#39;s default behavior of batching state updates for optimized performance.</p><h3>Basic Usage of flushSync</h3><p>Let’s start with a simple example</p><pre>import { flushSync } from &#39;react&#39;;<br><br>function Counter() {<br>  const [count, setCount] = React.useState(0);<br><br>  function handleClick() {<br>    flushSync(() =&gt; {<br>      setCount(c =&gt; c + 1);<br>    });<br>    // React has re-rendered at this point<br>    console.log(&#39;Count after flushSync:&#39;, count);<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;{count}&lt;/p&gt;<br>      &lt;button onClick={handleClick}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, clicking the button triggers an immediate re-render with the updated count, ensuring that any code following flushSync sees the updated state.</p><h3>When Not to Use flushSync</h3><p>While flushSync can be very useful, it&#39;s important to understand scenarios where it should be avoided:</p><ol><li>Avoid Regular State Updates: The default batching mechanism is efficient for most updates. Using flushSync unnecessarily can lead to performance drawbacks.</li><li>Not for Asynchronous Code: Implementing flushSync within asynchronous functions can lead to unpredictability in the UI&#39;s behavior.</li></ol><h3>Appropriate Use Cases for flushSync</h3><h4>Immediate Feedback Requirement</h4><p>In scenarios where immediate feedback to the user is critical, flushSync can be a lifesaver</p><pre>function ImmediateFeedbackComponent() {<br>  const [status, setStatus] = React.useState(&#39;&#39;);<br><br>  function handleSubmit() {<br>    flushSync(() =&gt; {<br>      setStatus(&#39;Submitting...&#39;);<br>    });<br>    // Perform submission logic<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleSubmit}&gt;Submit&lt;/button&gt;<br>      &lt;p&gt;{status}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>Complex State Dependencies</h4><p>When dealing with complex state logic where subsequent lines of code depend on the updated state</p><pre>function ComplexStateComponent() {<br>  const [value, setValue] = React.useState(0);<br>  const [derivedValue, setDerivedValue] = React.useState(0);<br><br>  function calculateDerivedValue() {<br>    // Complex calculation based on value<br>    return value * 2;<br>  }<br><br>  function updateValue(newValue) {<br>    flushSync(() =&gt; {<br>      setValue(newValue);<br>    });<br>    setDerivedValue(calculateDerivedValue());<br>  }<br><br>  // Render using value and derivedValue...<br>}</pre><h4>Integration with Non-React Libraries</h4><p>When using third-party libraries that need the DOM to be updated immediately</p><pre>function ExternalLibraryComponent() {<br>  const [data, setData] = React.useState(initialData);<br><br>  function handleUpdate(newData) {<br>    flushSync(() =&gt; {<br>      setData(newData);<br>    });<br>    externalLibrary.refresh(); // Needs the latest React updates<br>  }<br><br>  // Render using data...<br>}</pre><p>flushSync in React is a powerful tool, best used in specific scenarios requiring immediate UI updates or when dealing with complex state dependencies. Hope this article helps you use flushSync more often and for the right purpose.</p><p>Follow me for more content &amp; <a href="https://bmc.link/aliwhosane">buy me a coffee</a> if you are feeling super generous today!</p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b719ef8adc56" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/using-flushsync-in-react-b719ef8adc56">Using FlushSync in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebScraping with JavaScript]]></title>
            <link>https://javascript.plainenglish.io/webscraping-with-javascript-f85878d20ff0?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f85878d20ff0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 12:16:51 GMT</pubDate>
            <atom:updated>2024-06-16T18:33:48.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Want to learn scraping but not Python? You are at the right place and for those who don’t know… Web scraping refers to the technique of extracting data from websites. This process involves using automated software to visit web pages and collect specific information. It’s a powerful tool for data analysis, market research, and automated testing of web applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fe-vqU5awyNTZZWC-6YdFA.png" /><figcaption>img credits: Dall-E</figcaption></figure><h4>What is Puppeteer?</h4><p>Puppeteer is an open-source Node.js library that provides a high-level API to control Google’s Chrome or Chromium browser. It is available as an npm package and is primarily used for running browser sessions without a GUI. Puppeteer is particularly useful for tasks that require automating web interactions, such as form submissions, UI testing, scraping of JavaScript-generated content, and creating snapshots of web pages.</p><h4>Core Features of Puppeteer</h4><ol><li><strong>Automated Navigation: </strong>Puppeteer can programmatically navigate through web pages, click buttons, submit forms, and handle redirects, among other actions.</li><li><strong>Dynamic Content Scraping: </strong>Since Puppeteer controls a real browser, it can render and scrape content generated by JavaScript, making it ideal for dealing with modern web applications built with frameworks like React, Vue, or Angular.</li><li><strong>Screenshots and PDF Generation:</strong> Puppeteer can take screenshots of web pages for visual testing or archiving. It can also generate PDFs of web pages for reports or offline viewing.</li><li><strong>Automated Testing:</strong> Puppeteer integrates seamlessly with testing frameworks like Jest or Mocha, allowing for end-to-end testing of web applications.</li><li><strong>Network Interaction Monitoring:</strong> You can inspect network traffic to understand and test how your web application communicates with backend services.</li></ol><p>Let’s get started with actual implementation in Puppeteer</p><p><strong>a) Installation:</strong> Use the npm command to install this (I know you just skipped pass through this but have to write it for the one’s just getting started)</p><pre>npm install puppeteer</pre><p><strong>b) Launching a Headless Browser: </strong>Puppeteer scripts usually begin by launching a headless browser instance.</p><pre>const puppeteer = require(&#39;puppeteer&#39;);<br><br>(async () =&gt; {<br>  const browser = await puppeteer.launch();<br>  // Further actions go here<br>})();</pre><p><strong>c) Opening a Web Page:</strong> Open a new page in the browser and navigate to the desired URL</p><pre>const page = await browser.newPage();<br>await page.goto(&#39;https://example.com&#39;);</pre><p><strong>d) Interacting with the page: </strong>There are many ways you can interact with the page and page elements. Your imagination and page’s complexities are the limit here.</p><pre>// Clicking a button by its ID<br>await page.click(&#39;#submit-button&#39;); // this can also be done by other selectors<br><br>// Extracting text content of an element<br>const extractedText = await page.evaluate(() =&gt; document.querySelector(&#39;.content&#39;).textContent);<br><br>// Types &#39;myUsername&#39; into an input field with the ID &#39;username&#39;<br>await page.type(&#39;#username&#39;, &#39;myUsername&#39;);<br><br>// Selects the option with the value &#39;US&#39; in a dropdown with the ID &#39;country-select&#39;<br>await page.select(&#39;#country-select&#39;, &#39;India&#39;); <br><br>// Waits for an element with the class &#39;dynamic-content&#39; to appear<br>await page.waitForSelector(&#39;.dynamic-content&#39;); </pre><p><strong>e) Capturing Screenshots and Creating PDFs: </strong>This helps you create visual data of the entire process if you wish to use them for future reference, user stories, or presentations.</p><pre>// Taking a full-page screenshot<br>await page.screenshot({ path: &#39;full_page.png&#39;, fullPage: true });<br><br>// Generating a PDF file<br>await page.pdf({ path: &#39;page.pdf&#39;, format: &#39;A4&#39; });</pre><p><strong>f) Closing the Browser: </strong>Conclude your script by closing the browser to free resources</p><pre>await browser.close();</pre><p>There are a few more advanced techniques like Device Emulation, Handling Diaogbox, Intercepting network requests, etc that are out of the scope of this article and mostly won’t be useful for the scraping process.</p><blockquote>Ethical Considerations and Best Practices</blockquote><blockquote>When using Puppeteer for web scraping, it’s important to consider the legal and ethical implications. Respect the website’s terms of service, avoid overloading servers, and ensure data privacy and compliance with data protection laws.</blockquote><p>That is it for this article if you liked the article<strong> <em>hit the claps down below.</em></strong></p><p><strong>Follow me for more content &amp; if you are feeling super generous today you can </strong><a href="https://bmc.link/aliwhosane"><strong>buy me a coffee</strong></a><strong>.</strong></p><h4>Further Reading</h4><p><a href="https://javascript.plainenglish.io/how-to-scrape-an-e-commerce-site-using-a-web-scraping-tool-e2d14a37b374">How to Scrape an E-Commerce Site Using a Web Scraping Tool</a></p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f85878d20ff0" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/webscraping-with-javascript-f85878d20ff0">WebScraping with JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 18 with Redux Toolkit: A Simple Guide]]></title>
            <link>https://javascript.plainenglish.io/react-18-with-redux-toolkit-a-simple-guide-af71ee537123?source=rss-67475f8e93bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/af71ee537123</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ali Husen]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 08:16:54 GMT</pubDate>
            <atom:updated>2023-11-30T08:16:54.016Z</atom:updated>
            <content:encoded><![CDATA[<h3>React 18 with Redux Toolkit: A Simple Guide with Code Explanations</h3><p>React 18 introduced advanced features for building interactive UIs, and Redux Toolkit simplifies state management. Let us try and blend these together to make a perfect, developer-healthy smoothie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPi7lQ6E-wKR8zw-bfXSLw.png" /><figcaption>image src: Dall-E</figcaption></figure><p>I am assuming you already know the basics of React but we will still go over making a simple component before we go on integrating the Redux Toolkit.</p><pre>import React from &#39;react&#39;;<br><br>function Greeting() {<br>  return &lt;h1&gt;Welcome to React&lt;/h1&gt;;<br>}<br><br>export default Greeting;</pre><p>This code defines a Greeting component that renders a welcome message. It demonstrates how to create a simple React component that can be reused throughout your application.</p><p><strong>If you did not skip the above part and realized you did not know about it maybe switch to different articles and learn the basics of react first and then come back here as that is beyond the scope of this article.</strong></p><h3>Integrating Redux Toolkit</h3><p>Redux Toolkit streamlines state management in React applications.</p><p><strong>Setting Up Redux Toolkit</strong></p><ol><li>Install Redux Toolkit: Add Redux Toolkit to your project using npm or yarn whatever you prefer.</li></ol><pre>npm install @reduxjs/toolkit react-redux</pre><p>2. Configure the Store: Set up your Redux store</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br><br>export const store = configureStore({<br>  reducer: {<br>    // Reducers will be defined here<br>  },<br>});</pre><p>This code sets up the Redux store using configureStore. The store is the central location for your application&#39;s state, and reducers are functions that determine how the state changes.</p><p>3. Creating Slices: Define slices for state management</p><pre>import { createSlice } from &#39;@reduxjs/toolkit&#39;;<br><br>const exampleSlice = createSlice({<br>  name: &#39;example&#39;,<br>  initialState,<br>  reducers: {<br>    // Reducer logic here<br>  },<br>});<br><br>export const { actions } = exampleSlice;<br>export default exampleSlice.reducer;</pre><p>This snippet creates a slice named example. Slices are parts of the state, each managed by its own reducer and actions. This structure simplifies state management in large applications.</p><p>4. Dispatching Actions: Update the state using dispatch</p><pre>import { useDispatch } from &#39;react-redux&#39;;<br><br>const dispatch = useDispatch();<br>dispatch(actions.someAction());</pre><p>Here, the useDispatch hook from Redux is used to dispatch actions. Actions are objects that describe how the state should change, and dispatching an action triggers the reducers.</p><p>Let’s create a simple User data management to make things more clear.</p><pre>const userSlice = createSlice({<br>  name: &#39;user&#39;,<br>  initialState: { name: &#39;&#39;, age: 0 },<br>  reducers: {<br>    setUser(state, action) {<br>      state.name = action.payload.name;<br>      state.age = action.payload.age;<br>    },<br>  },<br>});<br><br>export const { setUser } = userSlice.actions;<br>export default userSlice.reducer;</pre><p>This userSlice manages the user&#39;s state. The setUser reducer updates the user&#39;s name and age. The slice&#39;s actions are exported for use throughout the application.</p><pre>dispatch(setUser({ name: &#39;John Doe&#39;, age: 30 }));</pre><p>This line dispatches the setUser action, updating the user&#39;s name to &#39;John Doe&#39; and age to 30. Dispatching actions is the primary method for triggering state changes in Redux.</p><p>I hope you understand how to use these 2 powerful tools better. I recommend making a couple of projects to get a hang of it. Also, try adding middleware to it which I haven’t covered in this simple implementation. All in all React 18 and Redux Toolkit offer a robust framework for building dynamic web applications.</p><p>Follow me for more content &amp; <a href="https://bmc.link/aliwhosane">buy me a coffee</a> if you are feeling super generous.</p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af71ee537123" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-18-with-redux-toolkit-a-simple-guide-af71ee537123">React 18 with Redux Toolkit: A Simple Guide</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>