Search code examples
reactjsreactjs-flux

In Flux what's the appropriate way for an action in one React component to affect another component?


I'm trying to wrap my head around Facebook's Flux...

Say I have an app with a side menu that can be hidden and shown via a button in the header.

My header is one component, my side menu is another component.

Currently my Header component just sets a class on the HTML div side menu element which gets animated to hidden by CSS.

What's the general idea here?


Solution

  • ReactJs doesn't really care about how it gets its data (how it's data is getting passed in or how that data should be handled across the web application). That's where Flux comes in, it creates a functional approach on how data is handled. Data-flow is essentially:

    Action -> Data Store -> Component
    

    Mutation of data happen through calling Actions. The Data Stores themselves have to listen on the actions and mutate the data within the store. This keeps the data structure and logic flat.

    In your case, your dataflow would probably look something like this:

    Header --> User Click --> Fires action --> Updates store --> Side menu listening and responding to that store change.

    Your case is a simple example which you probably don't really need Flux. I think it's easier if you have a parent component that maintains the view state logic, and use props/callbacks for the 2 children components (side menu and header). But a more advanced example that you need to make ajax calls and maintain session, Flux would become useful. Like if you have a Login Component, and you want to show different side-menu options and header options depending on user:

    Login Component --> User Logins --> Calls Action #signIn --> Showing Loading State
                                                             --> Dispatcher handles action (make api call to authenticate user and load user data)
    
    On success (for the api call), alert sessionStore, and populate store with data
    On error, maybe fire another action that says login failed or something
    
    SessionStore ---> Header Component (Listens to Store) --> Update view based on store information
                 ---> Side Menu Component (Listens to Store) --> Update