Autoplay

    Redux: Refactoring the Entry Point

    Dan AbramovDan Abramov

    We will learn how to better separate the code in the entry point to prepare it for adding the router.

    reactReact
    ^15.0.0
    reduxRedux
    ^3.0.0
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 I'm extracting the logic necessary to create the store, and to subscribe to it to persist the state into a separate file.

    00:09 I'm calling this file configure store, and so I'm creating a function called configure store that is going to contain this logic so that the app doesn't have to know exactly how the store is created and if we have any subscribe handlers on it. It can just use the return store in the index.js file.

    00:27 It is useful to export configure store rather than store itself, so that if you later write some tests, you can easily create as many store instances as you want. Now I can import configure store from my application's entry point, and I can use it right away without having to specify the reducer or the subscribers, because configure store takes care of that.

    00:53 I also want to extract the root rendered element into a separate component that I'm going to call root. It's going to accept the store as a prop, and it's going to be defined in a separate file in the components folder.

    01:08 I'm creating a new file called root. It needs to import React to use the JSX syntax, and I define inaudible functional component that just takes the store as a prop and returns an app inside a React Redux Provider.

    01:23 I need to import Provider from React Redux, and also import the app component they use, which is in the same folder. I can export the root component, and I can go back to my entry point, remove the outdated imports I no longer use, and instead import the root component from the components folder.

    01:45 Let's recap our refactoring. I moved all the code that is necessary for creating the store into a separate module. This module exports a function called configure store. It takes care of creating the store with the right reducer and the right initial state, and setting up any kinds of subscriptions, so that it returns a store that is ready for consumption by my application.

    02:11 I also moved the root component into a separate file. Currently, it is very simple. It just wraps the app into React Redux Provider. In the future, we can add something like a router here.

    Discuss

    Discuss