<?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 Akhilesh Krishnan on Medium]]></title>
        <description><![CDATA[Stories by Akhilesh Krishnan on Medium]]></description>
        <link>https://medium.com/@akhileshkrishnan?source=rss-a0127c8594ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*kNKXP0tBuLwn8vRiTkVwVQ.jpeg</url>
            <title>Stories by Akhilesh Krishnan on Medium</title>
            <link>https://medium.com/@akhileshkrishnan?source=rss-a0127c8594ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:38:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akhileshkrishnan/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[Creating a simple version of redux in an interview]]></title>
            <link>https://medium.com/@akhileshkrishnan/implementing-a-simple-version-of-redux-b30155944257?source=rss-a0127c8594ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/b30155944257</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Akhilesh Krishnan]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 08:10:34 GMT</pubDate>
            <atom:updated>2020-06-14T04:43:45.901Z</atom:updated>
            <content:encoded><![CDATA[<p>Create your own simple redux library when asked in an interview</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_-NaFaHus_yTblauq3QWw.png" /></figure><p>Implementing redux is asked in many interviews, many like me will usually get puzzled on hearing the question because the first question that rings in your mind is “<strong><em>how the hell am I supposed to implement such a complex library</em></strong>”. But don’t worry it will never be a worry the next time you face it. I am assuming that you are already familiar with using the redux library.</p><p>When you are asked to implement redux, it is basically to test</p><ul><li>your understanding of key principles of redux.</li><li>your knowledge of the basic purpose of why we use redux and how to implement a simple version of it.</li><li>your understanding of the data flow ie. what gets passed and what gets returned at each level.</li></ul><p><strong>Three principles of redux</strong></p><ol><li>Single source of truth: The global state of your application is stored in an object tree within a single-store.</li><li>The state is read-only: The only way to change the state is to emit an action, an object describing what happened.</li><li>Changes are made with pure function: To specify how the state tree is transformed by actions, you write pure reducers.</li></ol><p><strong>What are we planning to implement</strong></p><ol><li>reducer function</li><li><strong>createStore</strong>(reducer) : to create a redux store</li><li><strong>subscribe</strong>(subscriber) : method for adding subscribers</li><li><strong>dispatch</strong>(actionObject) : method to dispatch actions</li><li><strong>getState</strong>() : method to get the current state of data</li></ol><p>First, we&#39;ll need a reducer function that can be passed to our createStore function. For simplicity purpose, let&#39;s define a counter reducer which can either increment or decrement the count. The reducer we create will be a pure function ie. our function will not modify the input state provided but return a new copy of it.</p><ul><li><strong>Parameters</strong>: Current state object, action object</li><li><strong>Returns</strong>: State object</li></ul><pre>const initialState = {<br>  count: 0<br>};</pre><pre>const reducer = (state = initialState, action) =&gt; {<br>  switch (action.type) {<br>    case &#39;INCREMENT&#39;:<br>      return {<br>        ...state, count: state.count + 1<br>      };<br>    case &#39;DECREMENT&#39;:<br>      return {<br>        ...state, count: state.count - 1<br>      };<br>    default:<br>      return state;<br>  }<br>}</pre><p>Let’s now start with our actual redux implementation. First the createStore function</p><ul><li><strong>Parameter</strong>: reducer function</li><li><strong>Returns</strong>: Object containing methods</li></ul><p>Our createStore will return an object which has properties like subscribe, dispatch, getState inside it, so that we can call store.subscrbe(), store.dispatch() on the returned object.</p><pre>const createStore = reducer =&gt; {<br>  return {<br>    subscribe: () =&gt; {},<br>    dispatch: () =&gt; {},<br>    getState: () =&gt; {}<br>  };<br>};</pre><pre>// we could now call createStore like</pre><pre>const store = createStore(reducer);</pre><p>Next, the redux function should maintain a store object which will act as a central store for the application, its initial value should be the default value returned by the reducer. Do recollect that we always define an initialState when we code our reducer and this is the reason behind it.</p><p>This store object should not be directly modifiable and it should only be modified using a dispatch method. So we&#39;ll initialize it outside the returned object so that it is not accessible.</p><pre>const createStore = reducer =&gt; {<br>  let store = reducer(undefined, { type: &#39;<em>@@INIT&#39; </em>});<br>  return {<br>    // rest of our code<br>    .....<br>    .....<br>  };<br>};</pre><p>The reason behind passing undefined to the reducer is to force the reducer to consider its <strong>initialState </strong>as the initial store value, then we are passing an action object of type <strong><em>@@INIT</em></strong> as the second parameter so that reducer will execute the default case and return the unmodified <strong>initialState</strong>. Now our redux is generic to initialize the store with the value provided by the reducer which is using our redux.</p><p>Next, we need a method to return the current store object, lets define our <strong>getState </strong>for that</p><pre>const createStore = reducer =&gt; {<br>  let store = reducer(undefined, {});<br>  return {<br>    getState: () =&gt; {<br>      return store;<br>    }<br>  };<br>};</pre><p>Next, we will define a function to register subscriber functions, subscriber functions are the way components subscribe to store changes. Usually, there are multiple subscriber functions, so we’ll maintain a subscribers array and that way it can be used inside our dispatch method. You can think of subscriber function to be something similar to <strong>mapStateToProps(store) </strong>but an oversimplified version of it.</p><pre>const createStore = reducer =&gt; {<br>  let store = reducer(undefined, {});<br>  const subscriptions = [];<br>  return {<br>    getState: () =&gt; {<br>      return store;<br>    },<br>    subscribe: subscriber =&gt; {<br>      subscriptions.push(subscriber);<br>    }<br>  };<br>};</pre><p>Now the final part, our dispatch method. The dispatch method</p><ul><li><strong>Parameter</strong>: action object</li></ul><pre>dispatch: action =&gt; {<br>  const newState = reducer(store, action);<br>  if (newState !== store) {<br>    store = newState;<br>    subscriptions.forEach(subscriber =&gt; {<br>      subscriber(newState);<br>    });<br>  }<br>}</pre><ol><li>The first line is calling the reducer with the current store object and action object. So now the reducer will return an updated store object.</li><li>The if-condition in the second line is the basic way to check if the store data has been changed. Redux usually checks the reference to our existing store object and the new store object returned by the reducer, it assumes the data as changed only if the reference is different. This is the same reason why we do not mutate the store object inside the reducer rather return a new object every time.</li><li>The third line updates the redux store to the updated state object, hence the updated object will be our current store.</li><li>The fourth line is for invoking all the subscribers with updated store data since we have confirmed that the store data has been changed.</li></ol><p>We can test the working of our redux like this …</p><pre>const createStore = reducer =&gt; {<br>  let store = reducer(undefined, {});<br>  const subscriptions = [];<br>  return {<br>    getState: () =&gt; {<br>      return store;<br>    },<br>    dispatch: action =&gt; {<br>      const newState = reducer(store, action);<br>      if (newState !== store) {<br>        store = newState;<br>        subscriptions.forEach(callback =&gt; {<br>          callback(newState);<br>        });<br>      }<br>    },<br>    subscribe: subscriber =&gt; {<br>      subscriptions.push(subscriber);<br>    }<br>  };<br>};</pre><pre>// redux implementation ends here</pre><pre>const initialState = {<br>  count: 0<br>};</pre><pre>const reducer = (state = initialState, action) =&gt; {<br>  switch (action.type) {<br>    case &#39;INCREMENT&#39;:<br>      return {<br>        ...state, count: state.count + 1<br>      };<br>    case &#39;DECREMENT&#39;:<br>      return {<br>        ...state, count: state.count - 1<br>      };<br>    default:<br>      return state;<br>  }<br>}</pre><pre>const store = createStore(reducer);</pre><pre>const mapStateToProps = state =&gt; {<br>  console.log(&#39;state updated &#39;, state);<br>}</pre><pre>store.subscribe(mapStateToProps);</pre><pre>console.log(store.getState());</pre><pre>store.dispatch({ type: &#39;INCREMENT&#39; });<br>store.dispatch({ type: &#39;INCREMENT&#39; });<br>store.dispatch({ type: &#39;INCREMENT&#39; });<br>store.dispatch({ type: &#39;INCREMENT&#39; });</pre><pre>console.log(store.getState());</pre><pre>store.dispatch({ type: &#39;DECREMENT&#39; });<br>store.dispatch({ type: &#39;DECREMENT&#39; });<br>store.dispatch({ type: &#39;DECREMENT&#39; });</pre><pre>console.log(store.getState());</pre><p>Happy coding …. :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b30155944257" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>