<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Flux - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Flux - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 22 May 2026 17:40:33 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/flux/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Flux to Manage State in ReactJS - Explained with an Example ]]>
                </title>
                <description>
                    <![CDATA[ If you have started working on ReactJS recently then you might be wondering how to manage state in React so that your application can scale. To solve this state management issue, many companies and people have developed various solutions. Facebook, w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-flux-in-react-example/</link>
                <guid isPermaLink="false">66d460f973634435aafcefcc</guid>
                
                    <category>
                        <![CDATA[ Flux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sharvin Shah ]]>
                </dc:creator>
                <pubDate>Mon, 20 Apr 2020 19:25:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/04/Flux-4.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you have started working on ReactJS recently then you might be wondering how to manage state in React so that your application can scale.</p>
<p>To solve this state management issue, many companies and people have developed various solutions. Facebook, who developed ReactJS, came up with a solution called <a target="_blank" href="https://facebook.github.io/flux/"><strong>Flux</strong></a>.</p>
<p>You may have heard about <strong>Redux</strong> if you have worked on front end technology such as <strong>AngularJS</strong> or <strong>EmberJS</strong>. ReactJS also has a library for implementing Redux.</p>
<p>But before learning Redux I would advise you to go through Flux and understand it. After that give Redux a try. I say this because Redux is a more advanced version of Flux. If the concepts of Flux are clear then you can learn redux and integrate it into your application.</p>
<h2 id="heading-what-is-flux">What is flux?</h2>
<p>Flux uses a <strong>unidirectional data flow pattern</strong> to solve state management complexity. Remember it is not a framework – rather it's more of a pattern that targets to solve the state management issue.</p>
<p>Are you wondering what's wrong with the existing MVC framework? Imagine your client's application scales up. You have interaction between many models and views. How would it look?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Screenshot-2020-04-16-at-6.38.14-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Credit: Image from Facebook F8 Flux Event</em></p>
<p>The relationship between components gets complicated. It becomes hard to scale the application. Facebook faced the same issue. To solve this issue they architected a <strong>Single directional data flow</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Flux-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Credit: Image from Facebook's Flux Doc</em></p>
<p>As you can see from the image above, there are a lot of components used in Flux. Let's go through all the components one by one.</p>
<p><strong>View:</strong> this component renders the UI. Whenever any user interaction occurs on it (like an event) then it fires off the action. Also when the Store informs the View that some change has occurred, it re-renders itself. For example, if a user clicks the <strong>Add</strong> button.</p>
<p><strong>Action:</strong> this handles all the events. These events are passed by the view component. This layer is generally used to make API calls. Once the action is done it is dispatched using the Dispatcher. The action can be something like add a post, delete a post, or any other user interaction.</p>
<p>The common structure of the payload for dispatching an event is as follows:</p>
<pre><code class="lang-js">{
    <span class="hljs-attr">actionType</span>: <span class="hljs-string">""</span>,
    <span class="hljs-attr">data</span>: {
        <span class="hljs-attr">title</span>: <span class="hljs-string">"Understanding Flux step by step"</span>,
        <span class="hljs-attr">author</span>: <span class="hljs-string">"Sharvin"</span>
    }
}
</code></pre>
<p>The actionType key is compulsory and it is used by the dispatcher to pass updates to the related store. It is also a known practice to use constants to hold the value name for actionType key so no typos occur. Data holds the event information that we want to dispatch from Action to Store. The name for this key can be anything.</p>
<p><strong>Dispatcher:</strong> this is the central hub and singleton registry. It dispatches the payload from Actions to Store. Also makes sure that there are no cascading effects when an action is dispatched to the store. It ensures that no other action happens before the data layer has completed processing and storing operations.</p>
<p>Consider this component has a traffic controller in the system. It is a centralized list of callbacks. It invokes the callback and broadcasts the payload it received from the action.</p>
<p>Due to this component, the data flow is predictable. Every action updates the specific store with the callback that is registered with the dispatcher.</p>
<p><strong>Store:</strong> this holds the app state and is a data layer of this pattern. Do not consider it as a model from MVC. An application can have one or many app stores. Stores get updated because they have a callback that is registered using the dispatcher.</p>
<p>Node's event emitter is used to update the store and broadcast the update to view. The view never directly updates the application state. It is updated because of the changes to the store.</p>
<p>This is only part of Flux that can update the data. Interfaces implemented in the store are as follows:</p>
<ol>
<li><p>The <strong>EventEmitter</strong> is extended to inform the view that store data has been updated.</p>
</li>
<li><p>Listeners like <strong>addChangeListener</strong> and <strong>removeChangeListener</strong> are added.</p>
</li>
<li><p><strong>emitChange</strong> is used to emit the change.</p>
</li>
</ol>
<p>Consider the above diagram with more stores and views. Still, the pattern and the flow of data will be the same. This is because this is a single direction and predictable data flow, unlike MVC or Two-way binding. This improves the <strong>data consistency</strong> and it's <strong>easier to find the bug</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/Flux-Flow-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Flux Data Flow</em></p>
<p>Well, Flux brings the following key benefits to the table with the help of <strong>unidirectional data flow:</strong></p>
<ol>
<li><p>The code becomes quite clear and easy to understand.</p>
</li>
<li><p>Easily testable using Unit Test.</p>
</li>
<li><p>Scalable apps can be built.</p>
</li>
<li><p>Predictable data flow.</p>
</li>
</ol>
<blockquote>
<p><strong><em>Note:</em></strong> <em>The only drawback with the Flux is that there is some boilerplate that we need to write. Besides the boilerplate, there is little code we need to write when adding components to the existing application.</em></p>
</blockquote>
<h2 id="heading-application-template">Application Template</h2>
<p>To learn how to implement flux in ReactJS, we will build a Posts page. Here we will display all the posts. The application template is available at this <a target="_blank" href="https://github.com/Sharvin26/DummyBlog/tree/0d56987b2d461b794e7841302c9337eda1ad0725">commit</a>. We will use this as the template for integrating Flux on top of it.</p>
<p>To clone the code from this commit, use the following command:</p>
<pre><code class="lang-shell">git clone  https://github.com/Sharvin26/DummyBlog.git
</code></pre>
<pre><code class="lang-shell">git checkout 0d56987b2d461b794e7841302c9337eda1ad0725
</code></pre>
<p>We will require a <strong>react-router-dom</strong> and <strong>bootstrap</strong> module. To install these packages, use the following command:</p>
<pre><code class="lang-python">npm install react-router-dom@<span class="hljs-number">5.0</span><span class="hljs-number">.0</span> bootstrap@<span class="hljs-number">4.3</span><span class="hljs-number">.1</span>
</code></pre>
<p>Once done you'll see the following application:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/captured.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>DummyBlog</em></p>
<p>To understand Flux in detail we will only implement the <strong>GET</strong> posts page. Once that is done you'll realize the process is the same for <strong>POST</strong>, <strong>EDIT</strong> and <strong>DELETE</strong>.</p>
<p>Here you'll see the following directory structure:</p>
<pre><code class="lang-shell">+-- README.md 
+-- package-lock.json
+-- package.json
+-- node_modules
+-- .gitignore
+-- public
|   +-- index.html
+-- src
|   +-- +-- components
|   +-- +-- +-- common
|   +-- +-- +-- +-- NavBar.js
|   +-- +-- +-- PostLists.js
|    +-- +-- pages
|   +-- +-- +-- Home.js
|   +-- +-- +-- NotFound.js
|   +-- +-- +-- Posts.js
|   +-- index.js
|   +-- App.js
|   +-- db.json
</code></pre>
<blockquote>
<p><strong>Note:</strong> We have added here a <code>db.json</code> file. This is a dummy data file. Since we don't want to build APIs and instead focus on Flux, we will retrieve the data from this file.</p>
</blockquote>
<p>Our Application's base component is <code>index.js</code>. Here we have rendered the <code>App.js</code> inside the <code>index.html</code> under public directory using the <strong>render</strong> and <strong>getElementById</strong> methods. The <code>App.js</code> is used for configuring the routes.</p>
<p>We are also adding <strong>NavBar</strong> component at the top of the other so it will be available for all the components.</p>
<p>Inside the <strong>pages</strong> directory we have 3 files =&gt; <code>Home.js</code>, <code>Posts.js</code>, and <code>NotFound.js</code>. <code>Home.js</code> is simply used to display the Home component. When a user routes to a URL which doesn't exist, then <code>NotFound.js</code> renders.</p>
<p>The <code>Posts.js</code> is the parent component and it is used to get the data from the <code>db.json</code> file. It passes this data to the <code>PostLists.js</code> under the <strong>components</strong> directory. This component is a dumb component and it only handles the UI. It gets the data as props from its parent component (<code>Posts.js</code>) and displays it in the form of cards.</p>
<p>Now that we are clear about how our blog app is working we will start with integrating Flux on top of it.</p>
<h2 id="heading-integrating-flux">Integrating Flux</h2>
<p>Install Flux using the following command:</p>
<pre><code class="lang-shell">npm install flux@3.1.3
</code></pre>
<p>To integrate Flux in our application we will divide this section into 4 subsections:</p>
<ol>
<li><p>Dispatcher</p>
</li>
<li><p>Actions</p>
</li>
<li><p>Stores</p>
</li>
<li><p>View</p>
</li>
</ol>
<p>Note: The complete code is available at this <a target="_blank" href="https://github.com/Sharvin26/DummyBlog">repository</a>.</p>
<h3 id="heading-dispatcher">Dispatcher</h3>
<p>First, create two new folders named <strong>actions</strong> and <strong>stores</strong> under the <strong>src</strong> directory. After that create a file named <code>appDispatcher.js</code> under the same src directory.</p>
<p><strong>Note:</strong> From now all the files which are related to Flux will have <strong>Camel casing</strong> as they are not ReactJS components.</p>
<p>Go to the <code>appDispatcher.js</code> and copy-paste the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Dispatcher } <span class="hljs-keyword">from</span> <span class="hljs-string">"flux"</span>;
<span class="hljs-keyword">const</span> dispatcher = <span class="hljs-keyword">new</span> Dispatcher();
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> dispatcher;
</code></pre>
<p>Here we are importing the Dispatcher from the flux library that we installed, creating a new object and exporting it so that our actions module can use it.</p>
<h3 id="heading-actions">Actions</h3>
<p>Now go to the <strong>actions</strong> directory and create two files named <code>actionTypes.js</code> and <code>postActions.js</code>. In the <code>actionTypes.js</code> we will define the constants that we require in <code>postActions.js</code> and store module.</p>
<p>The reason behind defining constants is that we don't want to make typos. You don't have to define constants but it is generally considered a good practice.</p>
<pre><code class="lang-js"><span class="hljs-comment">// actionTypes.js</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
    <span class="hljs-attr">GET_POSTS</span>: <span class="hljs-string">"GET_POSTS"</span>,
};
</code></pre>
<p>Now inside the <code>postActions.js</code>, we will retrieve the data from <code>db.json</code> and use the dispatcher object to dispatch it.</p>
<pre><code class="lang-js"><span class="hljs-comment">//postActions.js</span>

<span class="hljs-keyword">import</span> dispatcher <span class="hljs-keyword">from</span> <span class="hljs-string">"../appDispatcher"</span>;
<span class="hljs-keyword">import</span> actionTypes <span class="hljs-keyword">from</span> <span class="hljs-string">"./actionTypes"</span>;
<span class="hljs-keyword">import</span> data <span class="hljs-keyword">from</span> <span class="hljs-string">"../db.json"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPosts</span>(<span class="hljs-params"></span>) </span>{
    dispatcher.dispatch({
        <span class="hljs-attr">actionTypes</span>: actionTypes.GET_POSTS,
        <span class="hljs-attr">posts</span>: data[<span class="hljs-string">"posts"</span>],
    });
}
</code></pre>
<p>Here in the above code, we have imported the dispatcher object, actionTypes constant, and data. We are using a dispatcher object's dispatch method to send the data to the store. The data in our case will be sent in the following format:</p>
<pre><code class="lang-json">{
    actionTypes: <span class="hljs-string">"GET_POSTS"</span>,
    posts: [
        {
            <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Hello World"</span>,
            <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Sharvin Shah"</span>,
            <span class="hljs-attr">"body"</span>: <span class="hljs-string">"Example of blog application"</span>
        },
        {
            <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Hello Again"</span>,
            <span class="hljs-attr">"author"</span>: <span class="hljs-string">"John Doe"</span>,
            <span class="hljs-attr">"body"</span>: <span class="hljs-string">"Testing another component"</span>
        }
    ]
}
</code></pre>
<h3 id="heading-stores">Stores</h3>
<p>Now we need to build the store which will act as a <strong>data layer</strong> for storing the posts. It will have an <strong>event listener</strong> to inform the view that something has changed, and will <strong>register</strong> using dispatcher with the actions to get the data.</p>
<p>Go to the store directory and create a new file called <code>postStore.js</code>. Now first, we will import <strong>EventEmitter</strong> from the Events package. It is available in the NodeJS by default. We will also import the dispatcher object and actionTypes constant file here.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { EventEmitter } <span class="hljs-keyword">from</span> <span class="hljs-string">"events"</span>;
<span class="hljs-keyword">import</span> dispatcher <span class="hljs-keyword">from</span> <span class="hljs-string">"../appDispatcher"</span>;
<span class="hljs-keyword">import</span> actionTypes <span class="hljs-keyword">from</span> <span class="hljs-string">"../actions/actionTypes"</span>;
</code></pre>
<p>We will declare the constant of the <strong>change</strong> event and a variable to hold the posts whenever the dispatcher passes it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> CHANGE_EVENT = <span class="hljs-string">"change"</span>;
<span class="hljs-keyword">let</span> _posts = [];
</code></pre>
<p>Now we will write a class that extends the <strong>EventEmitter</strong> as its base class. We will declare the following methods in this class:</p>
<p><code>addChangeListener</code>: It uses the NodeJS <strong>EventEmitter.on</strong>. It adds a change listener that accepts the callback function.</p>
<p><code>removeChangeListener</code>: It uses the NodeJS <strong>EventEmitter.removeListener*</strong>.* Whenever we don't want to listen for a specific event we use the following method.</p>
<p><code>emitChange</code>: It uses the NodeJS <strong>EventEmitter.emit*</strong>.* Whenever any change occurs, it emits that change.</p>
<p>This class will also have a method called <code>getPosts</code> which returns the variable <code>_posts</code> that we have declared above the class.</p>
<p>Below the variable declaration add the following code:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostStore</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">EventEmitter</span> </span>{
    addChangeListener(callback) {
        <span class="hljs-built_in">this</span>.on(CHANGE_EVENT, callback);
    }

    removeChangeListener(callback) {
        <span class="hljs-built_in">this</span>.removeListener(CHANGE_EVENT, callback);
    }

    emitChange() {
        <span class="hljs-built_in">this</span>.emit(CHANGE_EVENT);
    }

    getPosts() {
        <span class="hljs-keyword">return</span> _posts;
    }
}
</code></pre>
<p>Now create the <code>store</code> object of our PostStore class. We will export this object so that we can use it in the view.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> PostStore();
</code></pre>
<p>After that, we will use the dispatcher's <strong>register</strong> method to receive the payload from our Actions component.</p>
<p>To register for the specific event, we need to use the <code>actionTypes</code> value and determine which action has occurred and process the data accordingly. Add the following code below the object declaration:</p>
<pre><code class="lang-js">dispatcher.register(<span class="hljs-function">(<span class="hljs-params">action</span>) =&gt;</span> {
    <span class="hljs-keyword">switch</span> (action.actionTypes) {
        <span class="hljs-keyword">case</span> actionTypes.GET_POSTS:
            _posts = action.posts;
            store.emitChange();
            <span class="hljs-keyword">break</span>;
        <span class="hljs-keyword">default</span>:
    }
});
</code></pre>
<p>We will export the object from this module so others can use it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> store;
</code></pre>
<h3 id="heading-view">View</h3>
<p>Now we will update our view to send the event to <code>postActions</code> whenever our Posts page is loaded and receive the payload from the postStore. Go to <code>Posts.js</code> under the <strong>pages</strong> directory. You'll find the following code inside the <strong>useEffect</strong> method:</p>
<pre><code class="lang-js">useEffect(<span class="hljs-function">() =&gt;</span> {
    setposts(data[<span class="hljs-string">"posts"</span>]);
}, []);
</code></pre>
<p>We will change how our useEffect reads and updates the data. First, we will use the <code>addChangeListener</code> method from the postStore class and we will pass an <code>onChange</code> callback to it. We will set the <code>posts</code> state value to have a return value of the <code>getPosts</code> method from the <code>postStore.js</code> file.</p>
<p>At the start, the store will return an empty array as there is no data available. So we will call a <code>_getPosts_</code> method from the <code>postActions.js</code>. This method will read the data and pass it to the store. Then the store will emit the change and <code>addChangeListener</code> will listen to the change and update the value of the <code>posts</code> in its <code>onChange</code> callback.</p>
<p>If this seems confusing don't worry – check out the flow chart below which makes it easier to understand.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/FluxBlogFlow-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Remove the old code and update the following code inside <code>Posts.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> PostLists <span class="hljs-keyword">from</span> <span class="hljs-string">"../components/PostLists"</span>;
<span class="hljs-keyword">import</span> postStore <span class="hljs-keyword">from</span> <span class="hljs-string">"../stores/postStore"</span>;
<span class="hljs-keyword">import</span> { getPosts } <span class="hljs-keyword">from</span> <span class="hljs-string">"../actions/postActions"</span>;

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

    useEffect(<span class="hljs-function">() =&gt;</span> {
        postStore.addChangeListener(onChange);
        <span class="hljs-keyword">if</span> (postStore.getPosts().length === <span class="hljs-number">0</span>) getPosts();
        <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> postStore.removeChangeListener(onChange);
    }, []);

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onChange</span>(<span class="hljs-params"></span>) </span>{
        setPosts(postStore.getPosts());
    }

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">PostLists</span> <span class="hljs-attr">posts</span>=<span class="hljs-string">{posts}</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> PostPage;
</code></pre>
<p>Here you'll find that we have also removed the import and also we are using <code>setPosts</code> inside our callback instead of useEffect method. The <code>return () =&gt; postStore.removeChangeListener(onChange);</code> is used to remove the listener once the user leaves that page.</p>
<p>With this go to the Blog Page and you'll find that our blog app is working. The only difference is that now instead of reading the data in the <strong>useEffect</strong> method we are reading it in actions, storing it in the store, and sending it to the components that require it.</p>
<p>When using the actual API you'll find that the application loads the data from the API one time and stores it in the store. When we revisit the same page you'll observe that no API call is required again. You can monitor it under the source tab in Chrome Developer console.</p>
<p>And we're done!! I hope this tutorial has made the idea of Flux clearer and you'll be able to use it in your projects.</p>
<blockquote>
<p>Feel free to connect with me on <a target="_blank" href="https://twitter.com/sharvinshah26">Twitter</a> and <a target="_blank" href="https://github.com/Sharvin26">Github</a>.</p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Implement Redux in 24 Lines of JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Yazeed Bzadough 90% convention, 10% library. Redux is among the most important JavaScript libraries ever created. Inspired by prior art like Flux and Elm, Redux put JavaScript functional programming on the map by introducing a scalable architectur... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/redux-in-24-lines-of-code/</link>
                <guid isPermaLink="false">66d461b3d1ffc3d3eb89de82</guid>
                
                    <category>
                        <![CDATA[ Flux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Redux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 21 Oct 2019 12:59:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/cover-image-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yazeed Bzadough</p>
<p>90% convention, 10% library.</p>
<p>Redux is among the most important JavaScript libraries ever created. Inspired by prior art like <a target="_blank" href="https://facebook.github.io/flux/">Flux</a> and <a target="_blank" href="https://elm-lang.org">Elm</a>, Redux put JavaScript functional programming on the map by introducing a scalable architecture of three simple points.</p>
<p>If you're new to Redux, consider reading <a target="_blank" href="https://redux.js.org/introduction/three-principles">the official docs</a> first.</p>
<h2 id="heading-redux-is-mostly-convention">Redux Is Mostly Convention</h2>
<p>Consider this simple counter application that uses the Redux architecture. If you'd like to jump ahead check out <a target="_blank" href="https://github.com/yazeedb/implement-redux-counter-app">the Github repo</a> for it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/redux-counter-app-demo.gif" alt="redux-counter-app-demo" width="600" height="400" loading="lazy"></p>
<h3 id="heading-state-lives-in-a-single-tree">State lives in a single tree</h3>
<p>The application's state looks like this.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> initialState = { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> };
</code></pre>
<h3 id="heading-actions-declare-state-changes">Actions declare state changes</h3>
<p>By Redux convention, <strong>I do not</strong> directly modify (mutate) the state.</p>
<pre><code class="lang-js"><span class="hljs-comment">// DON'T do this in a Redux app</span>
state.count = <span class="hljs-number">1</span>;
</code></pre>
<p>Instead I create all the actions the user may leverage in the application.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> actions = {
  <span class="hljs-attr">increment</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'INCREMENT'</span> },
  <span class="hljs-attr">decrement</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'DECREMENT'</span> }
};
</code></pre>
<h3 id="heading-reducer-interprets-action-and-updates-state">Reducer interprets action and updates state</h3>
<p>The last architectural piece calls for a reducer, a pure function that returns a new copy of your state based on the previous state and action.</p>
<ul>
<li>If <code>increment</code> is fired, increment <code>state.count</code>.</li>
<li>If <code>decrement</code> is fired, decrement <code>state.count</code>.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> countReducer = <span class="hljs-function">(<span class="hljs-params">state = initialState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> actions.increment.type:
      <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span>
      };

    <span class="hljs-keyword">case</span> actions.decrement.type:
      <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span>
      };

    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<h3 id="heading-no-redux-so-far">No Redux so far</h3>
<p>Did you notice that we haven't touched the Redux library yet? We've just created some objects and a function. This is what I mean by "mostly convention", 90% of Redux doesn't require Redux!</p>
<h2 id="heading-lets-implement-redux">Let's implement Redux</h2>
<p>To put this architecture to use, we must plug it into a store. We'll implement just one function–<code>createStore</code>.</p>
<p>It's used like this.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>

<span class="hljs-keyword">const</span> store = createStore(countReducer);

store.subscribe(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(store.getState());
});

store.dispatch(actions.increment);
<span class="hljs-comment">// logs { count: 1 }</span>

store.dispatch(actions.increment);
<span class="hljs-comment">// logs { count: 2 }</span>

store.dispatch(actions.decrement);
<span class="hljs-comment">// logs { count: 1 }</span>
</code></pre>
<p>And here's our initial boilerplate. We'll need a list of listeners and the initial state supplied by the reducer.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> createStore = <span class="hljs-function">(<span class="hljs-params">yourReducer</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> listeners = [];
    <span class="hljs-keyword">let</span> currentState = yourReducer(<span class="hljs-literal">undefined</span>, {});
}
</code></pre>
<p>Whenever someone subscribes to our store, they get added to the <code>listeners</code> array. The is important because every time someone dispatches an action, all the <code>listeners</code> must be notified in a loop.</p>
<p>Calling <code>yourReducer</code> with <code>undefined</code> and an empty object returns the <code>initialState</code> we installed up above. This gives us a proper value to return when we call <code>store.getState()</code>. Speaking of which, let's create that method.</p>
<h3 id="heading-storegetstate">store.getState()</h3>
<p>This is a function that returns the latest state from the store. We'll need this to update our UI every time the user clicks a button.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> createStore = <span class="hljs-function">(<span class="hljs-params">yourReducer</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> listeners = [];
    <span class="hljs-keyword">let</span> currentState = yourReducer(<span class="hljs-literal">undefined</span>, {});

    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">getState</span>: <span class="hljs-function">() =&gt;</span> currentState
    };
}
</code></pre>
<h3 id="heading-storedispatchaction">store.dispatch(action)</h3>
<p>This is a function that takes an <code>action</code> as a parameter. It feeds that <code>action</code> and the <code>currentState</code> to <code>yourReducer</code> to get a <em>new</em> state. Then <code>dispatch</code> notifies everyone subscribed to the <code>store</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> createStore = <span class="hljs-function">(<span class="hljs-params">yourReducer</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> listeners = [];
  <span class="hljs-keyword">let</span> currentState = yourReducer(<span class="hljs-literal">undefined</span>, {});

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">getState</span>: <span class="hljs-function">() =&gt;</span> currentState,
    <span class="hljs-attr">dispatch</span>: <span class="hljs-function">(<span class="hljs-params">action</span>) =&gt;</span> {
      currentState = yourReducer(currentState, action);

      listeners.forEach(<span class="hljs-function">(<span class="hljs-params">listener</span>) =&gt;</span> {
        listener();
      });
    }
  };
};
</code></pre>
<h3 id="heading-storesubscribelistener">store.subscribe(listener)</h3>
<p>This is a function that lets you be notified when the store receives an action It's good to use <code>store.getState()</code> in here to get your latest state and update your UI.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> createStore = <span class="hljs-function">(<span class="hljs-params">yourReducer</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> listeners = [];
  <span class="hljs-keyword">let</span> currentState = yourReducer(<span class="hljs-literal">undefined</span>, {});

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">getState</span>: <span class="hljs-function">() =&gt;</span> currentState,
    <span class="hljs-attr">dispatch</span>: <span class="hljs-function">(<span class="hljs-params">action</span>) =&gt;</span> {
      currentState = yourReducer(currentState, action);

      listeners.forEach(<span class="hljs-function">(<span class="hljs-params">listener</span>) =&gt;</span> {
        listener();
      });
    },
    <span class="hljs-attr">subscribe</span>: <span class="hljs-function">(<span class="hljs-params">newListener</span>) =&gt;</span> {
      listeners.push(newListener);

      <span class="hljs-keyword">const</span> unsubscribe = <span class="hljs-function">() =&gt;</span> {
        listeners = listeners.filter(<span class="hljs-function">(<span class="hljs-params">l</span>) =&gt;</span> l !== newListener);
      };

      <span class="hljs-keyword">return</span> unsubscribe;
    }
  };
};
</code></pre>
<p><code>subscribe</code> returns a function called <code>unsubscribe</code> that you can call when you're no longer interested in listening to the store's updates.</p>
<h2 id="heading-all-together-now">All Together Now</h2>
<p>Let's hook this up to our buttons and view the final source code.</p>
<pre><code class="lang-js"><span class="hljs-comment">// simplified createStore function</span>
<span class="hljs-keyword">const</span> createStore = <span class="hljs-function">(<span class="hljs-params">yourReducer</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> listeners = [];
  <span class="hljs-keyword">let</span> currentState = yourReducer(<span class="hljs-literal">undefined</span>, {});

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">getState</span>: <span class="hljs-function">() =&gt;</span> currentState,
    <span class="hljs-attr">dispatch</span>: <span class="hljs-function">(<span class="hljs-params">action</span>) =&gt;</span> {
      currentState = yourReducer(currentState, action);

      listeners.forEach(<span class="hljs-function">(<span class="hljs-params">listener</span>) =&gt;</span> {
        listener();
      });
    },
    <span class="hljs-attr">subscribe</span>: <span class="hljs-function">(<span class="hljs-params">newListener</span>) =&gt;</span> {
      listeners.push(newListener);

      <span class="hljs-keyword">const</span> unsubscribe = <span class="hljs-function">() =&gt;</span> {
        listeners = listeners.filter(<span class="hljs-function">(<span class="hljs-params">l</span>) =&gt;</span> l !== newListener);
      };

      <span class="hljs-keyword">return</span> unsubscribe;
    }
  };
};

<span class="hljs-comment">// Redux architecture pieces</span>
<span class="hljs-keyword">const</span> initialState = { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> };

<span class="hljs-keyword">const</span> actions = {
  <span class="hljs-attr">increment</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'INCREMENT'</span> },
  <span class="hljs-attr">decrement</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'DECREMENT'</span> }
};

<span class="hljs-keyword">const</span> countReducer = <span class="hljs-function">(<span class="hljs-params">state = initialState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> actions.increment.type:
      <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span>
      };

    <span class="hljs-keyword">case</span> actions.decrement.type:
      <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span>
      };

    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};

<span class="hljs-keyword">const</span> store = createStore(countReducer);

<span class="hljs-comment">// DOM elements</span>
<span class="hljs-keyword">const</span> incrementButton = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.increment'</span>);
<span class="hljs-keyword">const</span> decrementButton = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.decrement'</span>);

<span class="hljs-comment">// Wire click events to actions</span>
incrementButton.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  store.dispatch(actions.increment);
});

decrementButton.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  store.dispatch(actions.decrement);
});

<span class="hljs-comment">// Initialize UI display</span>
<span class="hljs-keyword">const</span> counterDisplay = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'h1'</span>);
counterDisplay.innerHTML = <span class="hljs-built_in">parseInt</span>(initialState.count);

<span class="hljs-comment">// Update UI when an action fires</span>
store.subscribe(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> state = store.getState();

  counterDisplay.innerHTML = <span class="hljs-built_in">parseInt</span>(state.count);
});
</code></pre>
<p>And once again here's our final UI.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/redux-counter-app-demo.gif" alt="redux-counter-app-demo" width="600" height="400" loading="lazy"></p>
<p>If you're interested in the HTML/CSS I used, here's <a target="_blank" href="https://github.com/yazeedb/implement-redux-counter-app">the GitHub repo</a> again!</p>
<h2 id="heading-want-free-coaching">Want Free Coaching?</h2>
<p>If you'd like to schedule a free call to discuss Front-End development questions regarding code, interviews, career, or anything else <a target="_blank" href="https://twitter.com/yazeedBee">follow me on Twitter and DM me</a>.</p>
<p>After that if you enjoy our first meeting, we can discuss an ongoing coaching to help you reach your Front-End development goals!</p>
<h2 id="heading-wear-your-contributions">Wear Your Contributions</h2>
<p>If you're coding every day, especially if you're committing to GitHub, wouldn't it be cool to wear that contribution map for all to see?</p>
<p><a target="_blank" href="https://gitmerch.com/">Gitmerch.com</a> lets you print a t-shirt of your GitHub contribution map! Use the code, <strong>Yazeed</strong>, at checkout for a discount.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/git-merch-screenshot-1-1.png" alt="git-merch-screenshot-1-1" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/git-merch-screenshot-2-1.png" alt="git-merch-screenshot-2-1" width="600" height="400" loading="lazy"></p>
<h2 id="heading-thanks-for-reading">Thanks for reading</h2>
<p>For more content like this, check out <a href="https://yazeedb.com">https://yazeedb.com!</a></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to the Flux architectural pattern ]]>
                </title>
                <description>
                    <![CDATA[ By Cristian Salcescu Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority! Flux is an architectural pattern proposed by Facebook for building SPAs. It suggests to split the application into the fo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-introduction-to-the-flux-architectural-pattern-674ea74775c9/</link>
                <guid isPermaLink="false">66d45e073dce891ac3a967d4</guid>
                
                    <category>
                        <![CDATA[ Flux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 31 Jan 2019 18:23:03 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*7qtRmuWoMmFyhpnyxoS3MA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Cristian Salcescu</p>
<p><a target="_blank" href="https://read.amazon.com/kp/embed?asin=B07PBQJYYG&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=cm_sw_r_kb_dp_cm5KCbE5BDJGE"><strong>Discover Functional JavaScript</strong></a> was named one of the <a target="_blank" href="https://bookauthority.org/books/new-functional-programming-books?t=7p46zt&amp;s=award&amp;book=1095338781"><strong>best new Functional Programming books by BookAuthority</strong></a><strong>!</strong></p>
<p>Flux is an architectural pattern proposed by Facebook for building SPAs. It suggests to split the application into the following parts:</p>
<ul>
<li>Stores</li>
<li>Dispatcher</li>
<li>Views</li>
<li>Action / Action Creators</li>
</ul>
<h3 id="heading-store">Store</h3>
<p>Store manages the state. It can store both domain state and user interface state.</p>
<p>Store and state are different concepts. State is the data value. Store is a behavior object that manages state through methods. In the case of managing books: the book list is the state and BookStore manages that list.</p>
<p>A store manages multiple objects. It is the single source of truth in regards to those specific objects. In an application there can be many stores. For example: BookStore, AuthorStore, UserStore.</p>
<p>There are no setter methods on the store. You can only request state change by passing an action to the dispatcher.</p>
<p>A store listens for all actions and decides on which of them to act. This usually means a <code>switch</code> statement. Once the store has made the state changes, it will emit a change event. The store is an event emitter.</p>
<p>Stores don’t take other stores as dependencies.</p>
<h3 id="heading-dispatcher">Dispatcher</h3>
<p>Dispatcher is a single object that broadcasts actions/events to all registered stores. Stores need to register for events when the application starts.</p>
<p>When an action comes in, it will pass that action to all registered stores.</p>
<h3 id="heading-view">View</h3>
<p>View is the user interface component. It is responsible for rendering the user interface and for handling the user interaction. Views are in a tree structure.</p>
<p>Views listen for store changes and re-render.</p>
<p>Views can be further split in Presentation and Container Views.</p>
<p>Presentation views don’t connect to dispatcher or stores. They communicate only through their own properties.</p>
<p>Container views are connected to stores and dispatcher. They listen for events from stores and provide the data for presentation components. They get the new data using the stores’ public getter methods and then pass that data down the views tree.</p>
<p>Container views dispatch actions in response to user iteration.</p>
<h3 id="heading-actions">Actions</h3>
<p>An action is a plain object that contains all information necessary to do that action.</p>
<p>Actions have a <code>type</code> property identifying the action type.</p>
<p>As action objects move around the application, I suggest to make them immutable.</p>
<p>Actions may come from different places. They may come from views as a result of user interaction. They may come from other places like the initialization code, where data may be taken from a Web API and actions are fired to update the views. Action may come from a timer that requires screen updates.</p>
<h3 id="heading-action-creators">Action Creators</h3>
<p>The practice is to encapsulate the code, creating actions in functions. These functions that create and dispatch actions are called action creators.</p>
<h4 id="heading-web-api-calls">Web API Calls</h4>
<p>When doing Web API calls to update the user interface, the Web API call will be followed by an action to update the store. When the store is updated it will emit a change event and as result the view that listens for that event will re-render.</p>
<p>Web API calls are made in action creators. We can extract out the code that does the API call in Web API Utils functions.</p>
<h3 id="heading-unidirectional-data-flow">Unidirectional data flow</h3>
<p>Updating views flow in a single direction:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/B3swRnUORvq-CH8yZO-Pgy9ZiAmN5LPlgMM3" alt="Image" width="601" height="85" loading="lazy"></p>
<p>Views do not modify the data they received. They listen for changes of this data, create actions with new values, but do not update the data.</p>
<p>Stores, views and any other action can’t change the state in (other) stores directly. They must send an action through the dispatcher</p>
<p>The data flow is shorter in store reads than in writes.The data flow in store writes differs between asynchronous and synchronous actions.</p>
<p>Store Reads</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/toNPHVZBnlFDPKHyp142thO9y7f6tQzREs7T" alt="Image" width="274" height="81" loading="lazy"></p>
<p>Store Writes in synchronous actions</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/JQ2bHtD7C0rtKjNAHAYSD7TdPbRnV04WWyBg" alt="Image" width="599" height="88" loading="lazy"></p>
<p>Store Writes in asynchronous actions</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/U857Xuskoy-w6aGMC--FfAyIAUEyMj13JETi" alt="Image" width="599" height="222" loading="lazy"></p>
<h3 id="heading-pros">Pros</h3>
<p>Flux architecture is better in an application where views don’t map directly to domain stores. To put in a different way, when views can create actions that will update many stores and stores can trigger changes that will update many views.</p>
<p>Actions can be persisted and then replayed.</p>
<h3 id="heading-cons">Cons</h3>
<p>Flux can add unnecessary complexity to an application where each view maps to one store. In this kind of application a separation between view and store is enough.</p>
<p>Take a look for example at <a target="_blank" href="https://medium.freecodecamp.org/how-to-create-a-three-layer-application-with-react-8621741baca0">How to create a three layer application with React</a>.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Stores manage state. They change state only by listening for actions. Stores notify views to update.</p>
<p>Views render the user interface and handle user interaction. Container views listen for store changes.</p>
<p>The dispatcher broadcasts actions to all registered stores.</p>
<p>Actions are plain objects.</p>
<p><a target="_blank" href="https://read.amazon.com/kp/embed?asin=B07PBQJYYG&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=cm_sw_r_kb_dp_cm5KCbE5BDJGE&amp;source=post_page---------------------------"><strong>Discover Functional JavaScript</strong></a> was named one of the <a target="_blank" href="https://bookauthority.org/books/new-functional-programming-books?t=7p46zt&amp;s=award&amp;book=1095338781&amp;source=post_page---------------------------"><strong>best new Functional Programming books by BookAuthority</strong></a><strong>!</strong></p>
<p><strong>For more on applying functional programming techniques in React take a look at</strong> <a target="_blank" href="https://read.amazon.com/kp/embed?asin=B07S1NLFTS&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=cm_sw_r_kb_dp_Pko5CbA30383Y"><strong>Functional React</strong></a><strong>.</strong></p>
<p>Learn <strong>functional React</strong>, in a project-based way, with <a target="_blank" href="https://read.amazon.com/kp/embed?asin=B0846NRJYR&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=cm_sw_r_kb_dp_o.hlEbDD02JB2"><strong>Functional Architecture with React and Redux</strong></a><strong>.</strong></p>
<p><a target="_blank" href="https://twitter.com/cristi_salcescu">Follow on Twitter</a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
