<?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 Musema Hassen on Medium]]></title>
        <description><![CDATA[Stories by Musema Hassen on Medium]]></description>
        <link>https://medium.com/@musema.hassen?source=rss-a7fb8f91e192------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZOdGARiURXNX_wum</url>
            <title>Stories by Musema Hassen on Medium</title>
            <link>https://medium.com/@musema.hassen?source=rss-a7fb8f91e192------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:48:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@musema.hassen/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[React Higher Order Components — HOC]]></title>
            <link>https://medium.com/@musema.hassen/react-higher-order-components-hoc-ad2cc22153e4?source=rss-a7fb8f91e192------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad2cc22153e4</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react-hoc]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[higher-order-components]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Musema Hassen]]></dc:creator>
            <pubDate>Fri, 17 Feb 2023 11:26:48 GMT</pubDate>
            <atom:updated>2023-02-17T11:27:50.872Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Higher Order Components — HOC</h3><p>This article is assuming you have basic understanding of JavaScript and React.</p><ol><li>React: Higher Order Component(HOC) is a function which takes a react <strong>COMPONENT</strong> as param and return a <strong>COMPONENT</strong>.</li><li>JavaScript: Higher Order Function(HOF) is a function which takes a <strong>FUNCTION</strong> as parameter <strong>OR</strong> returns a <strong>FUNCTION</strong></li></ol><pre><br>export function withThemeContext(ComponentToWrap: React.FC): React.FC {<br> <br>    return function Wrapper(props): JSX.Element {<br>      const [themeType, setThemeType] = useState&lt;ThemeType&gt;(&#39;light&#39;);<br>      return (<br>            &lt;ThemeContext.Provider value={{ themeType, setThemeType}}&gt;<br>                    &lt;ComponentToWrap {...props} /&gt;<br>            &lt;/ThemeContext.Provider&gt;<br>        );<br>    };<br>}</pre><p>There quite lot of concepts packed in this code snippet, we will try break it down.</p><p>So in order to understand React HOC you need to be comfortable with JavaScript Higher Order Functions because <strong>HOC</strong> is just a variation <strong>HOF</strong>. I recommend reading this <a href="https://medium.com/@musema.hassen/the-secrets-of-understanding-react-js-3ae223c6df3b">article</a> to understand how React Function components essentially are JavaScript functions.</p><p><strong>withThemeContext</strong> : is a function which takes a <strong><em>Function</em></strong>( React.FC) as parameter and returns another <strong><em>Function</em></strong>( which is named Wrapper type of React.FC).</p><p>The function returned from <strong>withThemeContext </strong>is also a function, what this function does is it wraps the input component with ThemeContext that way we will be able to access the theme inside the component and it’s children components. This article is not about how React context works, if you’re not familiar with it, just imagine this withThemeContext HOC is providing some feature to the Wrapped component.</p><h4>Usage</h4><pre>function MyComponent() {<br>    // my component logic<br>}<br><br>const MyComponentWithThemeContext = withThemeContext(MyComponent);<br>// Now MyComponentWithThemeContext with the new Wrapper component returned from<br>// withThemeContext function<br><br>// app.tsx<br>function App(): JSX.Element {<br>  return &lt;MyComponentWithThemeContext /&gt;<br>}<br><br>// index.ts<br>ReactDOM.render(&lt;App/&gt;, document.getElementById(&#39;app&#39;));</pre><p>You might be asking why don’t we add the wrapper logic into MyComponent itself, that is possible. However imagine you have too many logics like this in your application, handling them in the same component gets complex very quickly. With this approach the HOC has only one goal, in this specific example withThemeContext has only one responsibility, managing the theme, which adheres <strong>Single Responsibility</strong> design principle.</p><p>Just to better understand the importance of this pattern, let’s assume you want to add ErrorBoundary to your component tree, to handle any unhandled exceptions in you app. What would you do? Should you change any of this components, NO. That is where HOC become handy, sometimes you can add more feature to your app without even touching any of the existing components, React Error Boundary is one of good examples. I have an article on this <a href="https://medium.com/@musema.hassen/react-error-boundaries-application-error-handling-4a07e6c5d7f">here</a> if you are interested.</p><pre>export function withErrorBoundary(ComponentToWrap: React.FC): React.FC {<br> <br>    return function Wrapper(props): JSX.Element {<br><br>      return &lt;ErrorBoundary&gt;<br>                 &lt;ComponentToWrap {...props} /&gt;<br>            &lt;/ErrorBoundary&gt;;<br>    };<br>}</pre><pre><br>const CompWithThemeContext = withThemeContext(MyComponent);<br>const CompWithErrorBoundary = withErrorBoundary(ComponentWithThemeContext);<br><br>// did you notice how the output of the first hoc passed to the other hoc<br>// this mean we are able to compose independent features together to build up application logic<br>// DECOMPOSITION then COMPOSITION = FLEXIBILITY + REUSABILITY + MANAGABILITY<br><br>// let&#39;s say now you have one more hoc, <br>// just implement it independently and follow the same pattern. like so<br><br>const CompWithAnotherFeature = withAnotherFeature(MyComponent);<br>const CompWithThemeContext = withThemeContext(CompWithAnotherFeature);<br>const CompWithErrorBoundary = withErrorBoundary(ComponentWithThemeContext);<br>// the above three lines are equivalent to the following<br>const Component = withErrorBoundary(withThemeContext(withAnotherFeature(MyComponent)));</pre><h3>Putting all together</h3><pre>// types.ts<br>export type ThemeType =  &#39;dark&#39; | &#39;light&#39;;<br><br>export interface IThemeContext {<br>    themeType: ThemeType;<br>    setThemeType: (themeType: ThemeType) =&gt; void;<br>}</pre><pre>// themeContext.ts <br><br>import { IThemeContext, ThemeType } from &#39;./types&#39;;<br>import React from &#39;react&#39;;<br><br>// create a reat context of type IThemeContext<br>const ThemeContext = React.createContext&lt;IThemeContext&gt;({} as IThemeContext);</pre><pre>// withThemeContext.tsx<br><br>export function withThemeContext(ComponentToWrap: React.FC): React.FC {<br> <br>    return function Wrapper(props): JSX.Element {<br>      const [themeType, setThemeType] = useState&lt;ThemeType&gt;(&#39;light&#39;);<br>      return (<br>            &lt;ThemeContext.Provider value={{ themeType, setThemeType}}&gt;<br>                    &lt;ComponentToWrap {...props} /&gt;<br>            &lt;/ThemeContext.Provider&gt;<br>        );<br>    };<br>}</pre><pre>import React, { useContext } from &#39;react&#39;;<br>import { ThemeContext } from &#39;./themeContext&#39;;<br><br>// This button provide the user to choose a theme<br>function ChangeThemeButton() {<br>    const { setThemeType } = useContext(ThemeContext);<br><br>    const onDarkClick = useCallback(() =&gt; { setThemeType(&#39;dark&#39;) }, []);<br>    const onLightClick = useCallback(() =&gt; { setThemeType(&#39;light&#39;) }, []);<br><br>    return (<br>      &lt;div&gt;<br>          &lt;button onClick={onLightClick}&gt;Change to light&lt;/button&gt;<br>          &lt;button onClick={onDarkClick}&gt;Change to dark&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>}</pre><pre>// withErrorBoundary.ts<br>export function withErrorBoundary(ComponentToWrap: React.FC): React.FC {<br> <br>    return function Wrapper(props): JSX.Element {<br>   <br>      return &lt;ErrorBoundary&gt;  // please check my other article for ErrorBoundary<br>                 &lt;ComponentToWrap {...props} /&gt;<br>            &lt;/ErrorBoundary&gt;;<br>    };<br>}</pre><pre>// myComposer.ts<br><br>const CompWithAnotherFeature = withAnotherFeature(MyComponent);<br>const CompWithThemeContext = withThemeContext(CompWithAnotherFeature);<br>const CompWithErrorBoundary = withErrorBoundary(ComponentWithThemeContext);<br><br>export { CompWithErrorBoundary as MyComponent }; // just renaming before exporting</pre><pre>// app.tsx<br>import React from &#39;react&#39;;<br>import { MyComponent } from &#39;./myComposer&#39;; // please note this is the renamed component<br><br>export function App() {<br><br>  return &lt;MyComponent /&gt;<br>}</pre><pre>// index.ts<br>import ReactDOM from &#39;react-dom&#39;;<br><br>ReactDOM.render(&lt;App/&gt;, document.getElementById(&#39;app&#39;));</pre><h3>Conclusion</h3><p>In this articale we discussed mainly HOC, however to try make the scenario more practical I used some other concepts which you may not familiar with. i.e. React Context API, React hooks, which will be discussing on other sessions. And there is also interesting topic about HOC vs Custom hooks. For most parts Custom Hooks can replace HOC in much better way but not completely.</p><h4><strong>Next Up</strong>: React Custom Hooks vs HOC</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad2cc22153e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observer Pattern JavaScript Implementation]]></title>
            <link>https://medium.com/@musema.hassen/observer-pattern-javascript-implementation-f4b0b0fddce2?source=rss-a7fb8f91e192------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4b0b0fddce2</guid>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[observer-design-pattern]]></category>
            <dc:creator><![CDATA[Musema Hassen]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 10:41:14 GMT</pubDate>
            <atom:updated>2023-02-15T20:34:49.401Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Subject manages a </em><em>dataor </em><em>state that may eventually changes which other parties( </em><em>Observers) are interested on.</em></p><pre>class Subject {<br>  state;<br>  observers = [];<br><br>  subscribe(observer) {<br>     this.observers.push(observer);<br>    }<br><br>  notify() {<br>    this.observers.forEach(observer =&gt; {<br>    observer.update(this.state);<br>    };<br>  }<br>}</pre><p>The above implementation covers core concepts of Observer pattern. Let’s break it down. The Subject exposes two methods:</p><ol><li>subscribe: It will let observers to subscribe for state changes.</li><li>notify It will notify all subscribers when state value is changed.</li></ol><p>Wait, who will change the state?</p><p>Yes, the Subject is responsible to managing or changing it’s state. When will it changes it? Well, that depends on the nature of the data or business requirement you are trying to achieve. For example, let’s say the sate was keeping track of market value of your favorite stock, you might want to update it in some interval.</p><p>Hmm, how do we achieve this then, in typical scenario, Subject also has one more method, which executes based on some conditions.</p><pre>class Subject {<br>  state;<br>  observers = [];<br>  .<br>  .<br>  .<br><br>  // Let&#39;s call some externl API every 1 second and update the state<br>  setState() {<br>    setInterval(() =&gt; {<br>          this.state = getUpdates(); // This function will execute every 1 sec<br>          this.notify(); // calling this method will call update method of all observers<br>    }, 1000);<br>  }<br>}</pre><p>Now, Subject can register Observers, change the state, notify Observers but where are those Observers? What do they look like?</p><p>In this specific implementation, the Subject is making one assumption about the observer, <em>If you are an object which has </em><em>updatemethod which can take state value as param you can observe my state.</em></p><pre>class Observer {<br>    update(state) {<br>      console.log(`I ${this.name} received state update: ${state}`)<br>    }<br>}</pre><p>Usage</p><pre>function MyApplication() {<br>  // create a subject<br>  const mySubject = new Subject();<br>  // let set the state value first time<br>  mySubject.setState();<br><br>  // we have subscribers aka observers<br><br>  const myObserver1 = new Observer();<br>  const myObserver2 = new Observer();<br>  <br>  // we have two observers which are related with the subject yet, let&#39;s do that<br>  <br>  mySubject.subscribe(observer1);<br><br>  // imagine the state changed at this point, do you think myObserver2 will get updates?<br>  // No myObserver2 is not subscribed yet<br><br>  // let myObserver2 subscribe so no future updates are missed<br>  mySubject.subscribe(myObserver2);<br>  // From now on, if any change in the sate both observers get updates<br>}</pre><p>Does the Subject, cares what Observers do with new updated state they receive? No, it’s up to the observer to decide what to do with the new updated state change. The responsibility of the Subject is notifying them that there is update.</p><p>What if the Observer no longer wants to receive updates? Did the Subject exposed any mechanism for observers to unsubscribe? No!!</p><p>unsubscribe</p><pre>class Subject {<br>  state;<br>  observers = [];<br>  .<br>  .<br>  .<br>  <br>  unsubscribe(observer) {<br>    const index = this.observers.indexOf(observer);<br>    if(index &gt;= 0)<br>    this.observers.splice(index, 1); // splice just delete the object in that index<br>  }<br>}</pre><p>Now, we can do something like so:</p><pre>mySubject.unsubscribe(observer1); // removes observer1 from the list</pre><p>Observers pattern ?? JavaScript ?? where are functions ?? can functions be Observers, Absolutely. I just chose object syntax to explain the pattern which I feel easier to understand, next post I will provide implementation of this pattern with functions as Observers.</p><h3>Conclusion:</h3><p>There are a variety of implementations of Observer pattern, However the core concept is the same. Focus on core concepts until you understand it, it may take a while to internalize it, that is OK, later once understand the concept you can customize however you like based on you requirements. <br>I will also share a little bit cleaner implementation on later posts, I find this implementation easier to explain.</p><p>Thank you!<br>Musema Hassen</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4b0b0fddce2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fluent API JavaScript/TypeScript Implementation]]></title>
            <link>https://medium.com/@musema.hassen/fluent-api-javascript-implementation-5dd00050ee44?source=rss-a7fb8f91e192------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dd00050ee44</guid>
            <category><![CDATA[fluent-api]]></category>
            <category><![CDATA[builders]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <dc:creator><![CDATA[Musema Hassen]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 11:03:46 GMT</pubDate>
            <atom:updated>2023-02-13T11:05:28.175Z</atom:updated>
            <content:encoded><![CDATA[<pre>interface IMyService {<br>  prop1: ISomeType1;<br>  prop2: ISomeType2;<br>}<br><br>class MyService implements IMyService {<br>  //<br>}</pre><h4>Scenario:</h4><ul><li>You want make sure prop1 and prop2 assigned some valid value before clients using instance of MyService class.</li><li>prop1 and prop2 are some complex values to construct.</li><li>Sometime you may have too many properties hard to pass in constructor.</li></ul><p>Wouldn’t it be nice if we can create those properties step by step and assign to the object? and validate those properties before the client is using it?</p><h4>Solution:</h4><ol><li>Create a builder class, and make the actual object private so consumers not accidentally using it before it’s ready to use.</li><li>The builder exposes public methods to set each properties in any order. <strong><em>The key point here is those methods need to return the instance of builder( </em></strong><strong><em>this) so that the consumer can call other public methods of the builder step by step.</em></strong></li><li>Expose the actual object with a method which you can validate it’s state before returning it.</li></ol><pre>export class MyServiceBuilder {<br>  private myService: IMyService;<br>  <br>  public withProp1(): MyServiceBuilder {<br>    // the logic of creating prop1 here<br>    const someValue = ...;<br>    this.myService.prop1 = someValue;<br>    // now return the builder itself, so client calls it&#39;s other methods<br>    return this;<br>  }<br><br>  public withProp2(): MyServiceBuilder {<br>    // the logic of creating prop2 here<br>    const someOtherValue = ...;<br>    this.myService.prop2 = someValue;<br>    // now return the builder itself, so client calls it&#39;s other methods<br>    return this;<br>  }<br>  <br>  public build(): IMyService {<br>  // here when build is called you can validate if prop1 and prop2 are assigned and valid<br>  // otherwise throw Error<br>  // this way making sure the build is only returning valid of myService object<br>  // now return the actual myService object   <br>  <br>  return this.myService;<br>  }<br>}</pre><h4>Usage</h4><pre>function myClientFunction() {<br>  const myService: IMyService = new MyServiceBuilder()<br>                                        .withProp1()<br>                                        .withProp2()<br>                                        .build();<br>}</pre><p>or</p><pre>function myClientFunction() {<br>  let myServiceBuilder= new MyServiceBuilder();<br>   myServiceBuilder = myServiceBuilder.withProp1(); // prop1 of myService is set<br>   myServiceBuilder = myServiceBuilder.withProp2(); // prop2 of myService is set<br>  // now builder sets all props of myService instance.<br>  //so we can get the constructed myService instance<br>   const myService: IMyService = myServiceBuilder.build(); // myService is READY<br>}</pre><h4>Conclusion</h4><p>This core idea in this patten is returning builder instance in setter methods, and returning the actual object from build method. <strong><em>Note</em></strong>: How you name the methods does’t really matter except for readability purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dd00050ee44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Secrets of understanding React.js]]></title>
            <link>https://medium.com/@musema.hassen/the-secrets-of-understanding-react-js-3ae223c6df3b?source=rss-a7fb8f91e192------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ae223c6df3b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[useeffect-hook]]></category>
            <dc:creator><![CDATA[Musema Hassen]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 11:00:45 GMT</pubDate>
            <atom:updated>2023-02-17T11:29:29.105Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In my opinion when a react application getting bigger and complex the main source of confusions comes from not understanding some fundamental JavaScript concepts i.e. Callbacks, Higher Order Functions(HOF), Promises, and Closures.</blockquote><p>Note: React components can be Class based or Function based. And there is no much difference conceptually. In this blog post we will be discussing Function component and JavaScript.</p><h3>Introduction</h3><p>In simple terms a react component is a JavaScript function which may return a <a href="https://beta.reactjs.org/learn/writing-markup-with-jsx">JSX Element</a> (markup which compiles to DOM/HTML element).</p><pre>function MyComponent() {<br>  const data = &#39;Some data&#39;;<br>  return &lt;div&gt; &lt;h1&gt; { data }&lt;/h1&gt; &lt;/div&gt;<br>}</pre><p>You might be wondering why does React mixes JavaScript and HTML together? Well, the main philosophy behind React is encapsulating UI rendering logic and markup lives together.</p><p>In this blog I will be focusing on explaining React components from JavaScript function point of view. <em>Please note Components and JavaScript functions may not be the same but they serve the same purpose.</em></p><p>Let’s see how we would call MyComponent function we defined above in both JavaScript and React way:</p><pre>MyComponent() // calling JavaScript function<br>&lt;MyComponent /&gt; // Rendering React component </pre><p>Essentially both are doing the same thing except the fact that if we are using it as pure JavaScript function JSX syntax is invalid. That is where transpilers like Babel, TypeScript comes in picture where JSX syntax is compiled to pure JavaScript DOM API.</p><p>Just to be very clear in this simple(MyComponent) example, this is how we would accomplish the same in JavaScript without React.</p><pre>//index.html<br>&lt;html&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>    &lt;script defer type=&quot;text/javascript&quot; src=&quot;./app.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;<br><br>// app.js<br>const myDiv = document.createElement(&#39;div&#39;);<br><br>const myH1 = document.createElement(&#39;h1&#39;);<br>myH1.innerHTML = &quot;Some data&quot;;<br><br>const myApp = document.getElementById(&#39;app&#39;); // get html element with id &quot;app&quot;<br><br>myDiv.appendChild(myH1);<br>// note: until this point nothing change in our DOM tree<br>myApp.appendChild(myDiv);<br>// now our DIV element which has H1 in it is added to DOM</pre><p>If we say this much about how JavaScript functions and React components are related, let’s focus on core concepts which are crucial to mastering React.js.</p><h3>Callbacks</h3><p>Callbacks are functions the <strong><em>caller</em></strong> passes to <strong><em>callee</em></strong> in parameter which the <em>callee</em> may eventually calls them.</p><pre>function myCallee(myNum, myCallback) {<br>  if(myNum%2 === 0){<br>    myCallback(&quot;Even number&quot;);<br>  } else {<br>    myCallback(&quot;Odd number&quot;);<br>  }<br>}<br><br>function myCaller() {<br>  function processResult(result) {<br>    console.log(result);<br>  }<br><br>  myCallee(20, processResult)<br>}<br><br>// execute the caller function<br><br>myCaller();</pre><p>As you can see when we try execute `<em>myCaller`</em> function it’s passing two arguments(20 and processResult) which will be assigned to the respective parameters of myCallee(myNum and myCallback). Here are important points to note.</p><ol><li>Once processResult is passed to myCallee as callback, myCallee id deciding when and how to call myCallback in this case processResult.</li><li>myCallee has no idea how the callback function was implemented internally, it just calls it with some value, in this case some string value.</li><li>Since JavaScript has no type checking, if caller was not passing a valid function, the application will fail, since the callee is treating it as a function and calling it back.</li><li>In general caller has no control on how and when the callback is going to be called, it may not call it at all.</li></ol><h3>Why understanding callback functions is important to better understand React?</h3><p>Let’s take a look one of the most popular react hook, useEffect.</p><p>Usage:</p><pre>import { useEffect } from &quot;react&quot;;<br><br>function SomeComponent() {<br>    // some other component logic<br>    useEffect(() =&gt; {<br>    // do something<br>  }, []);<br>  // retun some JSX<br>}</pre><p>Let’s try simplify it a little bit</p><pre>function SomeComponent() {<br>    useEffect(() =&gt; {<br>      // do some thing<br>  });<br>}</pre><p>Were you able to identify the caller, callee, and callback?</p><pre><strong>SomeComponent</strong>: was the caller, which is calling useEffect function.<br><strong>useEffect</strong>: is the callee, which <strong>SomeComponent</strong> is calling it.<br><strong>Arrow Function</strong>: which was passed in to useEffect as the callback. </pre><p>We typically pass arrow functions as callback to <strong>useEffect</strong>. For the sake of clarity I will try simply <strong>SomeComponent</strong> further:</p><pre>function doSomeThing() {}<br><br>function SomeComponent() {<br>    useEffect(doSomeThing);<br>}</pre><p>Now you can clearly see <strong><em>doSomeThing</em></strong> was passed as callback to <strong><em>useEffect</em></strong> function. Also it’s important to note doSomeThing is defined outside the scope of <strong><em>SomeComponent</em></strong> function, that doesn’t really matter. Sometimes it could be a preferred to increase the readability of your component.</p><pre><strong>SomeComponent</strong>: <em>Caller</em><br><strong>useEffect</strong>: <em>Callee</em><br><strong>doSomeThing</strong>: <em>Callback</em></pre><p>Wait a second, so we said useEffect function will be calling our <strong><em>doSomeThing</em></strong> function which was passed as callback, but <strong><em>when</em></strong>?</p><p>I want bring my initial argument here, we were able to understand most of important concepts about how useEffect API works without even knowing why React added it to the library. That is because useEffect is just a pure JavaScript function which takes callback function as parameter which React will <em>eventually</em> calls it.</p><p>How does React <strong><em>useEffect</em></strong> hook actually works?</p><ol><li><strong><em>When</em></strong> Component function(SomeComponent) renders to the DOM first time, it will call useEffect function with the callback function, however useEffect will delay execution of callback function until the component finishes it first render.</li><li><strong>Why: </strong>Imagine you want fetch some data from API you don’t want show black screen to users until the data is ready. Instead what useEffect API allows you to do is show uses progress page or some data until the actual data from API ready.</li><li>How: Once the data is ready, DOM or UI will sync to reflect the changes.</li><li>useEffect hook, accepts a dependency array in second parameter, when any change on deps will result re-execution of callback.</li><li>Note: Not providing dep array at all may result in infinite loop, if you want run the callback only once pass empty [] dependency.</li><li>It’s guaranteed useEffect will execute the callback at least once even empty [] deps specified</li></ol><pre>function ProductComponent(props) {<br>    const [product, setProduct] = useState();<br><br>    useEffect(() =&gt; {<br>         async getProduct(){<br>          const product = await MyAPI.getProductByIdAsync(props.id);<br>          setProduct(product);<br>          }<br>        getProduct(); // useEffect can not take async functions so add wrapper<br>    }, [props]);<br><br>    return (<br>            &lt;div&gt;<br>                &lt;span&gt; {product.name} &lt;span&gt;<br>            &lt;/div&gt;<br>           );<br>  }<br><br><br>// component usage<br>function MyContainerComponent() {<br>  const id = &quot;1&quot;;<br><br>  return &lt;ProductComponent id={id} /&gt;;<br>}</pre><h3>Conclusion</h3><p>In this post we tried to discuss how understanding JavaScript callback functions are important to understand React better. This will be a series of posts we will be trying to discuss core React concepts and relating them with JavaScript whenever applicable. You are also welcome to choose any topics you want to discuss.</p><p><strong>Next up</strong>: <a href="https://medium.com/@musema.hassen/react-higher-order-components-hoc-ad2cc22153e4"><em>Higher Order Functions(HOF) vs Higher Order Components(HOC)</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ae223c6df3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Promises simplified]]></title>
            <link>https://medium.com/@musema.hassen/javascript-promises-simplified-5105cb069ba2?source=rss-a7fb8f91e192------2</link>
            <guid isPermaLink="false">https://medium.com/p/5105cb069ba2</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asynchronous-javascript]]></category>
            <category><![CDATA[javascript-promise]]></category>
            <dc:creator><![CDATA[Musema Hassen]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 09:55:52 GMT</pubDate>
            <atom:updated>2022-01-27T08:35:36.903Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Promise</strong> is a powerful API which lets us to write and execute asynchronous code with less effort. Most of the time we execute promises provided by someone else. In this short tutorial I will try to discuss how we can create a promise when it is needed.</p><h4><strong>Creating a AND Executing Promise</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e59eb74f8e99e88bb5e7ba49e458f5c/href">https://medium.com/media/7e59eb74f8e99e88bb5e7ba49e458f5c/href</a></iframe><h4>Important notes</h4><ul><li>Whatever data passed in to resolve(data) will be passed to callback function passed to the then() function</li><li>Whatever reason passed in to reject(reason) will be passed to callback function passed to the catch() function</li><li>If you never called resolve inside promise, the then() function will never be called.</li><li>If you never called reject inside promise, the catch() function will never be called.</li><li>If a callback passed in to then(cb) or catch(cb) returns a promise we can chain them in the same way.</li><li>If you have called resolve, reject will never be called and vice versa.</li></ul><p><em>So what do you think will happen if neither of (resolve and reject) functions has been called? The promise will still execute the code asynchronously but neither of (then and catch) will be called.</em></p><h4>Demo</h4><p>In this demo code I will create a promise to get a list of repositories from <strong><em>https://api.github.com/repositories</em></strong> and display only 5 of them is html body. In real world you would use APIs like <strong><em>fetch</em></strong>(<em>which return promise</em>) to deal with this kind of scenarios. But for the purpose of this demo I am going to use XMLHttpRequest API.</p><p><strong><em>displayReposInsideHtmlBody : </em></strong>a utility function to display some data in the html body, nothing related with promises. Nothing fancy here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c8c9aaa9ffa8fb0b1e3e0c764a20c2a/href">https://medium.com/media/6c8c9aaa9ffa8fb0b1e3e0c764a20c2a/href</a></iframe><p>Create a <strong>getGitReposPromise </strong>promise which fetch a list of repositories from github.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10c5c24e136ecc144bfab902709e349c/href">https://medium.com/media/10c5c24e136ecc144bfab902709e349c/href</a></iframe><p>Execute the <strong><em>getGitReposPromise </em></strong>promise</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d91146892134931f7def6508c7f0ac8/href">https://medium.com/media/7d91146892134931f7def6508c7f0ac8/href</a></iframe><p>Body of index.html file where we display the data</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0376e036fca1d9ec5da207492908565d/href">https://medium.com/media/0376e036fca1d9ec5da207492908565d/href</a></iframe><blockquote><strong>Conclusion</strong></blockquote><p>In most cases you don’t need to create Promises from scratch, instead you would probably need consume promises created by someone else or other libraries. However it’s really important to understand how Promises work behind the scene.</p><blockquote>A complete demo is can be found <a href="https://github.com/musema/javascript-promises/blob/master/promiseExample.js">here</a>, downoad/clone the repo and open index.html file.</blockquote><p>For detailed explanation check <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">MDN</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5105cb069ba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Error Boundaries / Application Error Handling]]></title>
            <link>https://medium.com/@musema.hassen/react-error-boundaries-application-error-handling-4a07e6c5d7f?source=rss-a7fb8f91e192------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a07e6c5d7f</guid>
            <category><![CDATA[react-error-boundary]]></category>
            <category><![CDATA[error-boundaries]]></category>
            <category><![CDATA[react-error-handling]]></category>
            <dc:creator><![CDATA[Musema Hassen]]></dc:creator>
            <pubDate>Sat, 08 Feb 2020 05:56:45 GMT</pubDate>
            <atom:updated>2020-02-15T05:17:55.277Z</atom:updated>
            <content:encoded><![CDATA[<p>When error occurs in your react app you want to show your users a friendly message. Specially if you are developing a reusable component that will be used in another apps, you don’t want the error to propagate to the parent app, which may break the entire app.</p><p>So how do you handle error that may occur in your component gracefully?</p><p>Since react follows declarative paradigm we can’t use imperative try {} catch(){} approach.<a href="https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2"> Declarative vs Imperative Programming</a></p><p>React introduces <a href="https://reactjs.org/docs/error-boundaries.html">Error Boundaries</a> to solve this issue. The idea is defining error boundary component which we can use as a wrapper to our app so that when error occurs inside our app react will fires lifecycle methods(getDerivedStateFromError and componentDidCatch) defined in error boundary component where we can put our logic to choose what to be displayed(rendered).</p><p>React introduces <a href="https://reactjs.org/docs/error-boundaries.html">Error Boundaries</a> to solve this issue. The idea is defining error boundary component which we can use as a wrapper to our app so that when error occurs inside our app react will fires lifecycle methods(getDerivedStateFromError and componentDidCatch) defined in error boundary component where we can put our logic to choose what to be displayed(rendered).</p><p><em>We are going to use 4 components to demo this.</em></p><p><strong><em>App</em></strong>: Simple react component which will contain our app logic which eventually throw exception</p><p><strong><em>AppFallbackUI</em></strong>: A component to display if error occurred.</p><p><strong><em>AppErrorBoundary</em></strong>: A react Error boundary component which will define two lifecycle methods getDerivedStateFromError and componentDidCatch. It will detect any error occurred inside its child components and render appropriate component, App or AppFallbackUI component</p><p><strong><em>AppWithErrorBoundary</em></strong>: Wrapper component which wraps App component with AppErrorBoundary so that any error inside App with be detected.</p><pre>// App.js <br>import React from “react”;</pre><pre>const <strong>App </strong>= () =&gt; {</pre><pre>const person = null;</pre><pre>return <br>     &lt;div style={{ margin: “50px”, background: “lightgrey”}}&gt;               <br>        &lt;h1&gt;Person App&lt;/h1&gt;<br>        {person.name} {/* <strong><em>accessing null object</em></strong>, person is null*/}<br>     &lt;/div&gt;<br>}</pre><pre>export default App;</pre><pre>// AppFallbackUI.js<br>// This will be rendered when error thrown</pre><pre>import React from “react”;</pre><pre>export const <strong>AppFallbackUI </strong>= () =&gt; {</pre><pre>      return <br>           &lt;div style={{ margin: “50px”, background: “#FFBABA”}}&gt;            </pre><pre>            &lt;h3&gt;Sorry,w&#39;re experiencing technical difficulties.&lt;/h3&gt;</pre><pre>          &lt;/div&gt;<br>  }</pre><pre>// AppErrorBoundary.js<br>// React error boundary where error lifecycle methods defined</pre><pre>import React from ‘react’;<br>import { AppFallbackUI } from “./AppFallbackUI”;<br>import { logger } from “../services/logger”;</pre><pre>export class <strong>AppErrorBoundary </strong>extends React.Component {<br>        <strong><em>constructor</em></strong>(props) {<br>          super(props);<br>          this.state = { errorFound: false };<br>       }</pre><pre>      static <strong><em>getDerivedStateFromError</em></strong>(error) {<br>     // see the render to see how this affects what to be rendered.<br>     return { errorFound: true };<br>   }</pre><pre>     <strong><em>componentDidCatch</em></strong>(error) {<br>       logger.logError(error); // simple logger imported above<br>     }</pre><pre>   <strong>render</strong>() {</pre><pre>       if (<strong>this.state.errorFound</strong>) {<br>           return &lt;AppFallbackUI /&gt; {/* error detected */}<br>       }</pre><pre>     else {<br>       return this.props.children; {/* No error flow */}<br>     }</pre><pre>  }</pre><pre>}</pre><pre>export default AppErrorBoundary;</pre><pre>// AppWithErrorBoundary.js<br>// Wrapper to App component, this can be HOC but simplicity</pre><pre>import React from ‘react’;<br>import AppErrorBoundary from ‘./AppErrorBoundary’;<br>import App from ‘./App’;</pre><pre>export const <strong>AppWithErrorBoundary </strong>= () =&gt; &lt;AppErrorBoundary&gt;</pre><pre>              &lt;App/&gt;</pre><pre>        &lt;/AppErrorBoundary&gt;</pre><pre>// index.js <br>// finally in index.js </pre><pre>import React from ‘react’;<br>import ReactDOM from ‘react-dom’;<br>import {AppWithErrorBoundary } from ‘./components/AppWithErrorBoundary’;</pre><pre>ReactDOM.render(&lt;AppWithErrorBoundary /&gt;, document.getElementById(‘root’));</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a07e6c5d7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>