12 ms·
Things to learn in React before using Redux
- tchaffee 9y agoWorth a read. It summarizes in one place much of what I learned bit by bit from various other articles.
- k__ 9y agoMy first project with React was a mess, mostly because of Redux. Not because it's bad, but because the lead dev was adamant about using something Flux like. First we had Flummox, than he rewrote everything in a week with Redux, that was 2 years ago, before Redux had sane async helpers. In my current project (where I'm the lead, haha) I'm trying to got state/props all the way. I think for most apps it's more than enough AND it's easier to get started for new devs. React is really easy. I mean coming from Ember and ExtJS, its API is a walk in the park and you can get really far without extra state management. One thing that is important for this approach, minimize nesting. You don't want to pass down everything from the app, to the screen, to the list, to the item. etc. Instead of doing: <List items={items} /> do it like that <List> {items.map(i => <Item item={i}/>)} </List> No nesting of screens (top-level components), no (hidden) nesting of components. This may seem kinda strange, because the first example has no dependency to the Item component, but it gives the component that uses the List direct access, which simplifies props-passing immensely. This doesn't work for all apps, but it's a good starting point. I ended up with 2 folders, screens and components, that are both simply flat lists of component files.
- lilbobbytables 9y agoI partially blame every tutorial and contrived example of how you should use Redux. When first starting with React & Redux I spent some time thinking of where and how I should use Redux. Being that I was new to both, I didn't have any ingrained best practices, and it was hard to find any best practices around when to use redux. Every example seemed to use it for everything, which seemed insane to me in a real web app. I could see that the size and clutter would grow terribly, and for no obvious benefit. Your example above is similar to how many component libraries work (where you need to give the user flexibility). In a dashboard app, I'll make good use of Redux because there are often sets of data you revisit in different ways. In a more directory-like site I've recently built I use it to keep track of the logged in user information and high level information that dictates your experience (like user location), but nothing else.
- k__ 9y agoI try to keep it as simple as possible. But for complex dashboards I would probably use some observable based solution.
- peruvian 9y ago> I partially blame every tutorial and contrived example of how you should use Redux. Partially? No. The culture of side projects/GitHub/blog post had led people to over engineer their learning materials and side projects to look as employable as possible. Why make a todo list with just React when you can use Redux in it too and put it in your resume?
- k__ 9y agoHe he true. When I do a side project I often want to do fancy stuff and blog about it. When I get paid for my work, I try to keep it simple, because I fear I could end up with too much intermingled stuff I won't understand anymore after a few months.
- softawre 9y agoWanting to do fancy stuff for a side project is understandable. I'd prefer my team do that, so they can learn new stuff - and only bring the techniques/tools that actually work to paid projects.
- acemarke 9y agoFor what it's worth, my links list has a very large section of articles on Redux architecture and best practices: https://github.com/markerikson/react-redux-links/blob/master/redux-architecture.md https://github.com/markerikson/react-redux-links/blob/master... . Mapbox's post on "Redux for state management in large web apps" is particularly good: https://www.mapbox.com/blog/redux-for-state-management-in-large-web-apps/ https://www.mapbox.com/blog/redux-for-state-management-in-la... .
- Kiro 9y agoHow will you solve two components deep down different branches that share state?
- k__ 9y agofor shared state I used localStorage/AsyncStorage and added an event emitter to it.
- laurent123456 9y agoIn this kind of setup, I'm wondering how you handle events that happen outside of the component? Let's say you have a background function, created with setTimeInterval, which after some time update an item. With Redux, you could dispatch an action UPDATE_ITEM, which would modify the items, and in turn update the connected component. However, without Redux how is your component going to know about this item update and update the list? Do you use some kind of event listener/dispatcher?
- badthingfactory 9y agoYou have a root component. Run the interval within that component where you have access to state.
- bendavis381 9y agoThat's essentially redux: root state.
- badthingfactory 9y agoIf that was "essentially redux", redux would have no reason for existence.
- RussianCow 9y agoExcept for the fact that it drastically lowers the amount of manual props passing you have to do, and allows you to achieve much better separation of concerns. It is essentially Redux, only much worse the more complex your app is.
- badthingfactory 9y ago> It is essentially Redux, only much worse the more complex your app is. so... not at all like Redux then. C# is essentially Python except it has different syntax and static typing.
- acemarke 9y agoThat approach may minimize props passing, but it also is going to cut down on chances to use `shouldComponentUpdate` to avoid unnecessary re-renders and improve performance. Depending on your app, that might not be an issue, but it's something to be aware of.
- Androider 9y agoIt's exactly the opposite. You want to make your props as specific to the component as possible to minimize re-renders and pass-through of props causes unnecessary work. <List items={items} /> will re-render (or at least completely unnecessarily re-evaluate shouldComponentUpdate) the List itself whenever any item has changed. <Item item={i} /> with a shouldComponentUpdate or better yet React.PureComponent will only re-render the single changed item.
- acemarke 9y agoI think we're sorta saying the same thing, but in different ways. If you have that separate `<List>` parent component, you can apply `sCU` there so that it only re-renders when some of the items have changed, and not when other parts of the application update. If you don't have the `<List>`, the parent component will always re-render and always at least start the render lifecycle process for the `<Item>` components, but they can also implement `sCU` to skip the actual re-render. The most optimized approach is to have normalized data in Redux. The parent component should retrieve an array of item IDs in its `mapState` so that it only re-renders when an item is added, removed, or reordered, and render children like `<Item id={itemId} />`. The `Item` components should be connected as well, and use their `mapState` functions to look up the corresponding item from the Redux state by ID. That way _they_ will only re-render when their specific item has changed.
- Androider 9y agoAlso, when you do use Redux, as in your nesting example don't pass props through components that don't have any need for them except they propagate the prop to someone else. It's absolutely fine to connect() a component deeper in the hierarchy. Passing everything down is an anti-pattern with Redux, separation of concerns still applies and the props of a component defines the API, don't clutter that API with unrelated things. Components only receiving props that they themselves need has kept things clean in our massive codebase, and allows you to effortlessly move things about and easily re-use components wherever it makes sense.
- acemarke 9y agoYep, absolutely. See the Redux FAQ entry on "connecting multiple components" for more info [0] . I also discussed how connecting more components affects performance in my blog post "Practical Redux, Part 6 - Connected Lists, Forms, and Performance" [1], and there's many additional articles that discuss connected components and performance concerns as well [2]. [0] http://redux.js.org/docs/faq/ReactRedux.html#react-multiple-components http://redux.js.org/docs/faq/ReactRedux.html#react-multiple-... [1] http://blog.isquaredsoftware.com/2017/01/practical-redux-part-6-connected-lists-forms-and-performance/ http://blog.isquaredsoftware.com/2017/01/practical-redux-par... [2] https://github.com/markerikson/react-redux-links/blob/master/react-performance.md#redux-performance https://github.com/markerikson/react-redux-links/blob/master...
- prance 9y agoI don't agree with the view that a component doesn't need a prop "itself" if it "only" passes it on to a child component. That child component is a part of the parent. If one decided that e.g. the child is too simple to warrant to be its own component and inlined its render() content in the parent instead, suddenly its used props would be needed by the parent "itself". Another thing to consider is that one tightly couples components to stores when connecting. So reusability of these components is hampered.
- pedalpete 9y agoIf was my understanding that if a component has a prop which changes, even if that prop is passed down the tree, the component will still update. This is one way I use redux, the connector watches for changes in state and then updates the component directly, rather than passing props down the tree.
- Y7ZCQtNo39 9y agoI've been doing React for a while now and I've ended up with the same structure: 2 main folders. One of them in the base components, which are in folders grouped by their corresponding REST service endpoint (so if you have 'Foo' and 'Bar' db tables, and API's, then I have 'Foo' and 'Bar' folders inside my 'components' folder. The other folder is my views. It's more of the integration layer for all of my components. Since views typically correspond to a page route, that's where most of my react-router stuff is. It also is where I call the react-redux 'connect' HOC, to get data that is fed down into the components. So far it's working pretty well for me. I think it works great for a medium-size type of app.
- rednotebook 9y agobetter yet - don't create functions, especially inside a loop, in your render function, getItem = i => <Item item={i}/> ... <List> {items.map(getItem)} </List>
- TotallyHuman 9y agoI don't understand why anyone would use React at all with the ridiculous license.
- pbasista 9y agoWhat is wrong with its license?
- nilliams 9y agoThey're referring to the 'patent retaliation clause', see: https://medium.com/@dwalsh.sdlr/react-facebook-and-the-revokable-patent-license-why-its-a-paper-25c40c50b562 https://medium.com/@dwalsh.sdlr/react-facebook-and-the-revok...
- YCode 9y agoLogically following the conversation.... What's wrong with their patent retaliation clause? The link you provided basically says it only matters if you are a patent troll.
- nilliams 9y agoYeah I don't have a stake/opinion, just posted that particular article because it's a recent, thorough take, by a lawyer.
- enraged_camel 9y agoWell, there are many reasons to use React (the large ecosystem means you can find libraries and tutorials easily, for example) but yes, the license is a deal breaker for many, especially larger companies with legal teams who actually understand the ramifications.
- YCode 9y agoMicrosoft has no problem using React -- what are the ramifications?
- hippich 9y agoAs a general rule do not use `this.react` inside `setState({ ... })` - this will cause you problems eventually due state updates being async. If you need to use state to set new state, use functional callback instead - https://facebook.github.io/react/docs/react-component.html#setstate https://facebook.github.io/react/docs/react-component.html#s...
- captainmuon 9y agoI wish React would come with a standard way to handle Ajax (or a convention or semi-standard library would emerge). (Edit: "comes along" in the sense that immutability-helpers, redux and create-react-app come along with react. I'm not proposing to add anything to the react module. I'm not the world's best expert on react, but before downvoting can you please assume I know a little bit of what I'm talking about?) Something that: - Can fetch JSON according to criteria from an API - Caches stuff locally (just in memory, or in local storage) in case of duplicate calls - Deals with multiple concurrent calls, and merge them (e.g. fetching 1 and then 2,3,4 before 1 finishes -> either cancel 1, or wait until it finishes, and then fetch only the last requested item. - And all the stuff I can't think about right now, like cancellation and timeouts Plug your pure component into one of these, tell it about your API, and you're done. It's really error prone to write these containers yourself. And I think Redux doesn't really help much with Ajax.
- fokinsean 9y agoThis is one thing I miss about Ember. We recently moved to React and I'm really starting to miss Ember Data (even though it can be very picky).
- k__ 9y agoI plan to use it in a React-Native app for a JSON/REST API. Why not, isn't it standalone?
- spicyj 9y agoI haven't used Ember Data much. I'd be curious how you think it could apply or could be ported to React. Maybe you'd have time to write up a short gist of what you wish you could write in React?
- vasilakisfil 9y agoYes Ember-Data was great thing to have in Ember, something I miss from React ecosystem. In the early days was a bit unstable but now it's super stable and flexible (serializers/adapters customization etc). I think there should be an initiative to get it out of Ember so that you can use it with other projects as well.
- sghiassy 9y agoThe rush to use Redux for every React project is one of the most annoying parts of the React community; using a tool just to use it, before understanding if you need it or not. This article summarizes a lot of good points.
- nfriedly 9y agoAgreed. Until recently, my team was responsible for most of the official IBM Watson service demos, and we standardized on React for those and built up a nice library of react components[1]. None of them used Redux, though, because in general it just wasn't needed. When we handed off responsibility of these demos to the individual service teams, we wrote up guidelines that specifically recommended React but not Redux - with the logic that if the demo is getting to a point where Redux is providing value, then it's probably too complex for a demo. Our new project is a more involved web app that includes lots of state, shared across many different components, and we're making great use of Redux there. [1]: https://watson-developer-cloud.github.io/react-components/ https://watson-developer-cloud.github.io/react-components/
- matsemann 9y agoOne of the things I find hardest with redux is to make reusable components (across projects), as they have to be added to the state tree somewhere, and then connected. With nested components you may get implicit dependencies on where in the tree it should be. All this makes it very cumbersome. So even though most of our apps use Redux, the reusable parts use setState as they then can be completely independent.
- acemarke 9y agoYeah, that is a tradeoff - globalized state makes a lot of scenarios easier, but does make complete encapsulation and reusability harder. Most of the third-party "Redux-connected component" libs I've seen provide a reducer that they expect to be added to the root of the state tree under a specific key name. Works, but it's not ideal. I've seen a few that let you provide a selector or key name when you initialize the library, so that the library is more flexible in how it's connected. There's been a lot of discussion of various approaches for implementing fully encapsulated/reusable Redux-based React components in Sebastian Lorber's "Scalable Frontend with Elm or Redux" repo [0], and my links list has a section of additional articles on the topic of encapsulation with Redux [1]. My Redux addons catalog also has a large section for libraries that implement some form of per-component state or component encapsulation in Redux as well [2]. So, it's not impossible, but it does take work and there are tradeoffs either way. [0] https://github.com/slorber/scalable-frontend-with-elm-or-redux https://github.com/slorber/scalable-frontend-with-elm-or-red... [1] https://github.com/markerikson/react-redux-links/blob/master/redux-architecture.md#encapsulation-and-reusability https://github.com/markerikson/react-redux-links/blob/master... [2] https://github.com/markerikson/redux-ecosystem-links/blob/master/component-state.md https://github.com/markerikson/redux-ecosystem-links/blob/ma...
- acemarke 9y agoAs usual, this is an excellent article by Robin. Well-written, and full of great information. It's worth noting that both the React and Redux teams (including Dan Abramov and myself) agree that you should focus on learning React first, and _then_ learn Redux. That way there's fewer new concepts and terms to learn at once, and once you understand React, you'll have a better appreciation for what kinds of problems Redux can help solve. That's not to say you _can't_ learn them both at once, just that it's the suggested approach that will work best for most people.
- bernadus_edwin 9y agoPeople should learn eventEmitter or PubSub before learn redux
- RussianCow 9y agoWhy?
- bernadus_edwin 9y agoRedux is too complex and too many line of code. Most of activity why need redux are async fetch and eventEmitter notification. My advice is try eventEmitter first. If u need more, than jump to redux or mobx. The main reason use redux is if u need time travel
- noncoml 9y agoIMHO Redux is a heavy, clunky and awkward practice that is only holding React back. My advice to anyone reading this forum is give MobX a try before deciding to commit to Redux.
- ng12 9y agoDon't kid yourself, MobX comes with it's own baggage. Both are great libraries, both have advantages, both have drawbacks.
- tomduncalf 9y agoWhat are the downsides of MobX that you've come across? The main ones I've encountered are not being sure why something isn't reacting (always my fault but not always that easy to track down), odd interop issues with observables actually being "proxy" objects (e.g. useless console.log unless you call toJS), I guess no middleware-type concept or Saga type side effect management (never really used middleware in Redux and disliked all the ceremony around side effects)... that's all I can think of right now but curious to know others experiences. I honestly can't imagine any reason I'd go back to Redux aside from if it was used on a project I was working on though. I can develop so much faster and with fewer bugs (as typechecking MobX code thoroughly is much easier than Redux with Typescript) that there's no comparison, and like the OP, I think everyone should try it out - you'll almost definitely be pleasantly surprised!
- aidos 9y agoI've been working with it recently. The lack of prescriptiveness is an issue generally. No different from not having a library, but it's worth considering. The library itself works really well. Use strict mode and everything is super fast and reliable. Today we've been evaluating mobx-state-tree. It has some noise (not as bad as redux). It's opinionated which helps to remove architecture decisions. So far it looks promising.
- ng12 9y ago
- spinlock 9y agoI'd rather use Redux without React than React without Redux. Sure there's some boilerplate but we use typescript so the redux boilerplate seems trivial in comparison. Redux keeps your app _simple_. That's not the same as easy. It means that you can reason about your app as it grows and new features are added. When you run into problems like: this page is taking too long to load because we do calculations x, y and z on the server to push the data to the app. But z takes forever to compute and makes the initial page load painful. With Redux, you can move z to an async endpoint and just load x and y on page load (put the component that needs z in a loading state). Then, fire an ajax request when the component mounts to get z. When that call returns, it updates your store and the component that needs z transitions from loading to loaded. I took me a couple of hours to do the above in a Redux app and decrease the page load from 2 seconds to 300ms. And it didn't add complexity to the app that would make it difficult to maintain. I don't even want to think how long that refactor would take if the state had been managed with React. And ... don't even get me started on how easy -- and fast -- it is to test a Redux app. Zero side-effects means zero setup and teardown between specs.
- deleted 9y ago[deleted]