Take the case of reseting a password. The user is presented with a form asking them to enter their email. They submit the form so that they'll be sent a reset link in an email. The submit triggers an action, the action makes a POST to /api/password/reset and will return success or failure.
Obviously i want to update the UI so the user knows what is going on. The Flux way is to have actions dispatch a constant e.g. PASSWORD_RESET_SUCCESS and stores listen to the dispatcher so they can change the state. Components listen to the stores so they change the UI when the store state changes.
In the case of the password reset, i can't really see a sensible way to have this run through a store (and it seems verbose to do so). The only changing of state seems to be directly related to that form/component. Nothing that needs to be preserved once the user has left that page.
Is it "flux-y" to have components listen directly to the dispatcher?
Is there a sensible design for a store that allows me to handle generic events like this that don't directly link to models in the app?
Many thanks!
(This relates to working on https://github.com/mwillmott/techbikers in case anyone is interested)
No, it isn't. The architecture of the Flux should always follow the same scenario — Component calls actionCreator, ActionCreator dispatches actions to the stores, store emits change to all subscribed components. That is how Flux works, explained here.
I think the best way to do it is to have the general ResultStore, which simply accepts key/value defined in the action and writes them to hash. This way you can get away with one handler, with the name onResultWrite or something like this. Flux Stores were never meant to be a direct representation of your models — they are more a representation of your whole app state.
Flux architecture obviously can seem too strict and complex for the simple app — and it is. But it was not designed for simple apps in mind, it was designed for the complicated UI with lots of components — as complicated as the get. That's why stores, actions and components need to be separated from themselves as much as possible.
If you think that your application is quite simple, you can always take shortcuts, like passing a changeState callback directly to the action as a param — but if some other component will need to react to the PASSWORD_RESET_SUCCESS event, you've got yourself a problem. You can always think about it when it happens though. The project architecture is always about trade-offs, flexibility vs development speed vs performance.
The most important skill of developer is to know about this trade-offs, their value and know where to make them — and where not.
Good luck!
Related
I may choose to put some states as component states, and I thought that's what useState() is for.
However, the book Learning React, O'Reilly, 1st Ed, 2nd Release, p. 185, said:
With Redux, we pull state management away from React entirely.
Also, in the official Redux website, the example "Real World" also even make isFetching a Redux state, instead of component state. (Its GitHub repo).
I also found that in some project in some company, coworkers seem to favor everything as Redux state even when it can be a component state.
For example, in that same book, p. 185, it said we even keep which messages is expanded or not into the Redux store. But which message is expanded, seems entirely local to this component and it has nothing whatsoever to do with other components at all. In the case of isFetching, as least I can understand it that what if the whole app wants to unite the isFetching of any component into a global spinner indicator.
This webpage also says:
The solution in idiomatic React – i.e., code that was written the way an experienced React developer would write it – is to have what's called a single source of truth, which is one master state for most if not all of your application, then send that state down as props to your child components.
be a pragmatic programmer: go for stateless components where possible
I don't quite understand it. How does it work? When a state can be a component state, would it be perfectly ok to put it as component state? Or in React / Redux, the rule is to make everything into a Redux state? (in such case, then what is useState() for?)
Update: I like #RemcoGerlich's answer, and I put two links as a comment under his answer. Those are official docs stating "Don't put all states into Redux".
It is an eternal discussion. There are several types of state that have their own best ways to solve them:
Navigation related state, to go to different "pages" or kinds of views in your application. For this, using the browser URL has many usability advantages, and using React Router is much more natural.
State retrieved from the backend through its API, this isn't really state of your frontend at all, you have a cache. For this a library like React Query is much more suited (it handles e.g. your "isFetching" state, as well as reloading things after a while).
Small bits of state that only have local significance, like whether a small control that hides some detail is now open or closed. I feel things that are used only locally should be stored only locally, like in useState.
Often the number of things left is quite small, and putting them in one or a few Contexts is fine, except if your application becomes quite complicated.
But, Redux comes with its own advantages -- a single way to make undo functionality, a way to serialize / rehydrate its entire state, and Redux dev tools that allow looking at the action history in case you find yourself debugging complicated effects to do with the order in which happened. If you use this heavily, then you would be inclined to store more state in Redux than you would if you only make a little use of these advantages.
So it's matter of degree, it's more art than exact science, there are no strict rules. "Put everything in Redux" certainly sounds suspect to me, but who knows about your team.
If your state and operations on that state are moderate in size then react Context API is really smart enough to support you. Even, #danAbrvmov writes:
React Redux uses context internally but it doesn’t expose this fact in the public API. So you should feel much safer using context via React Redux than directly because if it changes, the burden of updating the code will be on React Redux and not you.
You may like reading his article: You Might Not Need Redux
As for, you see some companies and projects using Redux, this is because Redux is out there for a long time and Context API is newer. Moreover, if you really need some features like redux-thunk, you can still use it.
I doubt you clearly understand how the state is handled in React.
In a typical React application, data is passed top-down (parent to child) via props. You may like my answer on another post to learn when we may need Context API or Redux at all: https://stackoverflow.com/a/62980048/9857078
Without some global state management library like Redux, what would be a good way to pass the user around through my components? I'm using Firebase, so I'm imagining my top-level app component will be listening to auth changes and storing the user somewhere. Here are the options I've thought of:
Passing 'user' to each route in props (and on to children that need it)
Using a global object of my own
Using Context
1 seems like a hassle.
2 doesn't seem like the right way and like more of a hassle, wouldn't I have to listen for changes and set the user in my states? It's what they show in the React Router docs but I'm guessing that's just for simplicity's sake and not best practice.
3 seems like the best way to me but it seems like it's discouraged:
The vast majority of applications do not need to use context.
If you
want your application to be stable, don't use context. It is an
experimental API and it is likely to break in future releases of
React.
I would still say that you use context. It's the best way I have found to thread a common state throughout the react tree.
Even though they discourage it, all popular react libraries (including react-redux) use it big time. It's not going to be removed any time soon. And the use case seems very legit, provided you know what you are doing.
I was wondering, how much state does really belong into the stores, and not into the components? I've read at some places that really all state should live inside the stores.
Would that include really component specific stuff, like input values (before submitting), input validation, if a modal is open, if something has been clicked etc?
What are the best practices here?
The obvious answer:
Keep component specific state (input value, modal open/ closed, stuff clicked, layout, formatting) inside the component state as much as possible.
And app specific state inside the store. Which includes, but is not limited to, stuff you send back and forth with a server.
That said, there is a lot of grey area here:
are filters applied to a search list component state? Or app state (if you save filters for future visits to the same page)?
are visited links in a global root-menu root-component state or app state?
if you are using optimistic updates, you may have a need to save user input stuff in the store, before and after communication with the server.
Some rules of thumb I use:
State belongs in component if it has the same lifecycle as the component (so if the state does not need to exist before the component mounts, and if it can be forgotten after the component unmounts)
If the state needs to be remembered when closing and reopening app, it is probably best put inside the store (where you do exchanges with server and/or localstorage)
If in doubt, start with state in component only: it keeps state much more localised (to the component) and keeps your code more manageable. At a later stage, you can always move the state to the store.
Keeping everything in flux stores may be benefitial for some apps.
So first, you should try to decide whether your app is like this.
If you're not sure whether a piece of state belongs to a flux store, then it's most likely that it doesn't.
You'll know when you need flux. And when you reach that level of understanding of whether such application architecture is appropriate for you, you'll probably know the answer to your initial question as well.
But of course it's nice to have some kind of specific guide, maybe just a mental guide, telling you when to keep state inside the component and when not to.
I'd go with these guides:
Is this state purely UI-related? Then you probably don't need to keep it in the store.
Is this state shared anywhere else outside the component? If not, then don't put it in the store. It's fine inside the component.
Can this state be persisted in the URL? If so, then don't put it in the store; put it in the url! It might be a search query of an input or a currently opened tab.
There may be exceptions to all of these, but in general I believe this to correspond well to the original ideas of a flux app.
P.S. Also I should say that there are a lot of talks saying that you should (may) keep all your UI inside an immutable state tree. That's how redux is introduced to lots of people. I think you should understand that while this is a great concept and it allows you so save/replay any user interactions, it is more often than not unnecessary and it's not what the main idea of Flux is about. And redux itself is a great flux tool that doesn't force you to keep all of the UI state in the stores.
View state specific to a component belongs in that component. App state which concerns many components belongs in a store.
It's debatable.
For example redux propose a pattern where ALL state belong in the store. Personally I think it is kind of impractical in many situations. It is very rare when I have any reason to store for example state of the button in the store.
But sometimes it can be advantageous. It is definitely easier to test when your whole app is stateless.
Outline
In my app I'm using React and Reflux and have a hierarchical setup with regards to my data. I'm trying to break elements of my app into separate stores to be able to hook events correctly and separate concerns.
I have the following data flow:
Workspaces -> Placeholders -> Elements
In this scenario, when a workspace is created a default placeholder must in turn be created with a reference (ID) to the newly created workspace. The same applies for the placeholder to element relationship.
Sticking point
The Reflux way seems to suggest the PlaceholderStore listens to the triggers from WorkspaceStore, adding the newly created ID to this.trigger().
Reflux only allows a single event to be triggered from stores; thus preventing external components being able to discern create or update actions. This means that if one trigger in the store sends an ID as argument[0], subsequent triggers should do the same (to remain consistent). This is a problem for components looking for updates to multiple workspaces (e.g. re-ordering / mass updates).
Undesirable solution
I had thought to add in a concept of StoreActions; Actions that only stores can create, that other stores would then listen to (effectively discarding the original trigger from stores). With this components / stores could listen to specific events, and the arguments passed to said events could be tailored without worry. This seems like a wrong way to go and an abuse of the Reflux event system.
Help
Should I be trying to break up related data? Is there a better way to structure the data instead?
I've read about aggregate stores, but not seen any implementations to dissect. Do these offer a solution by way of bringing data from multiple stores together, and if so, what is responsible for creating events React components can listen to?
Many thanks for any help / insight anyone can offer!
Yes, it is perfectly reasonable to call actions from a store. I see actions as initiators of data flows and I consider exceptional flows as seperate ones.
A good example is a CRUD store that also handles AJAX calls (to CRUD the data with server-side). The store will trigger the change event as soon as it's data gets updated. However in the event that an AJAX call fails, it should instead start a data flow for that instead so that other stores and components can listen in on those. From the top of my head such errors are in the interest of a toast/notification component and Analytics error logging such as GA Exceptions.
The AJAX example may also be implemented through the preEmit hook in the actions and there are several examples among the github issues discussion on that. There is even this "async actions" helper.
It's by design that the stores only emit a change event. If you want to emit other kinds of events, it basically means you're starting new data flows for which you should be using actions instead.
I'm getting to be a fan of David Nolen's Om library.
I want to build a not-too-big web app in our team, but I cannot really convince my teammates to switch to ClojureScript.
Is there a way I can use the principles used in om but building the app in JavaScript?
I'm thinking something like:
immutable-js or mori for immutable data structures
js-csp for CSP
just a normal javascript object for the app-state atom
immutable-js for cursors
something for keeping track of the app-state and sending notification base on cursors
I'm struggling with number 5 above.
Has anybody ventured into this territory or has any suggestions? Maybe someone has tried building a react.js app using immutable-js?
Edit July 2015: currently the most promising framework based on immutability is Redux! take a look! It does not use cursors like Om (neither Om Next does not use cursors).
Cursors are not really scalable, despite using CQRS principles described below, it still creates too much boilerplate in components, that is hard to maintain, and add friction when you want to move components around in an existing app.
Also, it's not clear for many devs on when to use and not use cursors, and I see devs using cursors in place they should not be used, making the components less reusable that components taking simple props.
Redux uses connect(), and clearly explains when to use it (container components), and when not to (stateless/reusable components). It solves the boilerplate problem of passing down cursors down the tree, and performs greatly without too much compromises.
I've written about drawbacks of not using connect() here
Despite not using cursors anymore, most parts of my answer remains valid IMHO
I have done it myself in our startup internal framework atom-react
Some alternatives in JS are Morearty, React-cursors, Omniscient or Baobab
At that time there was no immutable-js yet and I didn't do the migration, still using plain JS objects (frozen).
I don't think using a persistent data structures lib is really required unless you have very large lists that you modify/copy often. You could use these projects when you notice performance problems as an optimization but it does not seem to be required to implement the Om's concepts to leverage shouldComponentUpdate. One thing that can be interesting is the part of immutable-js about batching mutations. But anyway I still think it's optimization and is not a core prerequisite to have very decent performances with React using Om's concepts.
You can find our opensource code here:
It has the concept of a Clojurescript Atom which is a swappable reference to an immutable object (frozen with DeepFreeze). It also has the concept of transaction, in case you want multiple parts of the state to be updated atomically. And you can listen to the Atom changes (end of transaction) to trigger the React rendering.
It has the concept of cursor, like in Om (like a functional lens). It permits for components to be able to render the state, but also modify it easily. This is handy for forms as you can link to cursors directly for 2-way data binding:
<input type="text" valueLink={this.linkCursor(myCursor)}/>
It has the concept of pure render, optimized out of the box, like in Om
Differences with Om:
No local state (this.setState(o) forbidden)
In Atom-React components, you can't have a local component state. All the state is stored outside of React. Unless you have integration needs of existing Js libraries (you can still use regular React classes), you store all the state in the Atom (even for async/loading values) and the whole app rerenders itself from the main React component. React is then just a templating engine, very efficient, that transform a JSON state into DOM. I find this very handy because I can log the current Atom state on every render, and then debugging the rendering code is so easy. Thanks to out of the box shouldComponentUpdate it is fast enough, that I can even rerender the full app whenever a user press a new keyboard key on a text input, or hover a button with a mouse. Even on a mobile phone!
Opinionated way to manage state (inspired by CQRS/EventSourcing and Flux)
Atom-React have a very opinionated way to manage the state inspired by Flux and CQRS. Once you have all your state outside of React, and you have an efficient way to transform that JSON state to DOM, you will find out that the remaining difficulty is to manage your JSON state.
Some of these difficulties encountered are:
How to handle asynchronous values
How to handle visual effects requiring DOM changes (mouse hover or focus for exemple)
How to organise your state so that it scales on a large team
Where to fire the ajax requests.
So I end up with the notion of Store, inspired by the Facebook Flux architecture.
The point is that I really dislike the fact that a Flux store can actually depend on another, requiring to orchestrate actions through a complex dispatcher. And you end up having to understand the state of multiple stores to be able to render them.
In Atom-React, the Store is just a "reserved namespace" inside the state hold by the Atom.
So I prefer all stores to be updated from an event stream of what happened in the application. Each store is independant, and does not access the data of other stores (exactly like in a CQRS architecture, where components receive exactly the same events, are hosted in different machines, and manage their own state like they want to). This makes it easier to maintain as when you are developping a new component you just have to understand only the state of one store. This somehow leads to data duplication because now multiple stores may have to keep the same data in some cases (for exemple, on a SPA, it is probable you want the current user id in many places of your app). But if 2 stores put the same object in their state (coming from an event) this actually does not consume any additional data as this is still 1 object, referenced twice in the 2 different stores.
To understand the reasons behind this choice, you can read blog posts of CQRS leader Udi Dahan,The Fallacy Of ReUse and others about Autonomous Components.
So, a store is just a piece of code that receive events and updates its namespaced state in the Atom.
This moves the complexity of state management to another layer. Now the hardest is to define with precision which are your application events.
Note that this project is still very unstable and undocumented/not well tested. But we already use it here with great success. If you want to discuss about it or contribute, you can reach me on IRC: Sebastien-L in #reactjs.
This is what it feels to develop a SPA with this framework. Everytime it is rendered, with debug mode, you have:
The time it took to transform the JSON to Virtual DOM and apply it to the real DOM.
The state logged to help you debug your app
Wasted time thanks to React.addons.Perf
A path diff compared to previous state to easily know what has changed
Check this screenshot:
Some advantages that this kind of framework can bring that I have not explored so much yet:
You really have undo/redo built in (this worked out of the box in my real production app, not just a TodoMVC). However IMHO most of actions in many apps are actually producing side effects on a server, so it does not always make sens to reverse the UI to a previous state, as the previous state would be stale
You can record state snapshots, and load them in another browser. CircleCI has shown this in action on this video
You can record "videos" of user sessions in JSON format, send them to your backend server for debug or replay the video. You can live stream a user session to another browser for user assistance (or spying to check live UX behavior of your users). Sending states can be quite expensive but probably formats like Avro can help. Or if your app event stream is serializable you can simply stream those events. I already implemented that easily in the framework and it works in my production app (just for fun, it does not transmit anything to the backend yet)
Time traveling debugging ca be made possible like in ELM
I've made a video of the "record user session in JSON" feature for those interested.
You can have Om like app state without yet another React wrapper and with pure Flux - check it here https://github.com/steida/este That's my very complete React starter kit.