19 ms·
Things every React.js beginner should know
- kieranajp 11y agoGoogle cache: http://webcache.googleusercontent.com/search?q=cache:https://camjackson.net/post/9-things-every-reactjs-beginner-should-know http://webcache.googleusercontent.com/search?q=cache:https:/...
- camjackson 11y agoShould be back up now!
- darrhiggs 11y agoHey, thanks for this. With regards to redux-thunk, have you taken a look at redux-saga[0]? Any thoughts? [0] https://github.com/yelouafi/redux-saga https://github.com/yelouafi/redux-saga
- camjackson 11y agoI've seen it mentioned by a few people, including Redux creator Dan Abramov (who is very open about tweeting links to 'competing' libraries!), but I've only taken a brief look so far. My initial impression is that it seems really interesting, although I wonder if the use of generators will scare people away. Many devs are already exhausted with the number of new JavaScript features they're being told to learn. I definitely want to dig a bit deeper and try it out properly though.
- acemarke 11y agoBest comparison I've seen so far is that it's sort of like "background processing threads for Redux". The downside is that it might not mix well with time-travel debugging, because a saga effectively has its own internal state. That said, Dan Abramov does seem to think it's a very intriguing approach, so it's worth keeping an eye on.
- didgeoridoo 11y ago#10: This guide will be out of date in 3 months.
- elcct 11y agoGood that with Google you can limit your search to a certain time frame. Personally, when I Google stuff about React, I set filter to "Past month" so that most results are quite up to date. I wonder if in the future the project that you start doing in the morning will use outdated libs by the evening ;)
- marknutter 11y agoDoes this not seem like a problem to anybody else? Wasn't the whole point of React that it was supposed to be simple? And yet things have gotten so complex you're giving advice that anything older than 3 months isn't even worth reading?
- Retozi 11y agoI really don't understand the underlying complaint of your comment that the React ecosystem is in constant flux (see what I did there?) I've been writing React SPAs for roughly two years now. Very few things have changed. The first app I've written roughly looks like the newest one. Couple of lessons learned here and there like everywhere else. Yes, there are many Flux libraries and different implementations. However, a decent State management solution for React is roughly 200-300 LOC. So there are many of those 200-300 LOC libraries. So what? If it's a big project, you should spend the time to figure out what fits YOUR project and YOUR team the best. If it's a side project, use the most popular with the best documentation and be done with it.
- hex13 11y agoThe biggest advantage of this progress is that there is a lot experimentation with new kind of tools (for example Redux Dev Tools. This is fascinating. I mean Redux is great, but the fact that there are dedicated dev tools for this? Wow. I'm waiting for new tools (maybe every popular library from now on will have its own dev tools? Or maybe somebody will make universal dev tools for all React libraries?). I think what's happening inside React ecosystem and this constant flux of innovations is not comparable with anything in the webdev before (maybe except Ruby community which is also pretty innovative).
- deleted 11y ago[deleted]
- diggan 11y ago> 5. Use Redux.js Well, that is not really something every React.js beginner should know. Feels weird to say that a X beginner should learn framework Y since he is probably just interested in X... > 6. Always use propTypes Worth mentioning that this slows down your application since React needs to check all the props. Don't forget to set NODE_ENV=production when compiling your production script.
- awjr 11y agoIf you are learning MVC, only learning V is not going to get you far. I do wonder if things like Typescript can solve a lot of the speed issues.
- EvanPlaice 11y agoWhy would you assume Typescript solves any speed issues? Typescript's type checking adds overhead just the same. So it's also a good idea to disable checks during runtime.
- tlrobinson 11y agoTypeScript doesn't do any runtime checks, AFAIK. In fact, that's one of their stated goals: "Impose no runtime overhead on emitted programs." https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals https://github.com/Microsoft/TypeScript/wiki/TypeScript-Desi...
- EvanPlaice 11y agoTo-may-to, to-mah-to. That doesn't answer what I was asking. Fact: type checking is disabled during runtime. Why would one assume that Typescript somehow solves speed issues? It has no measurable impact on runtime performance.
- tlrobinson 11y agoI was addressing the second part of your comment. TypeScript is a static type checker. It operates at compile time. There is nothing to "disable" at runtime. But yes, regarding your original question, you are correct, aggressive optimization is a non-goal of TypeScript. It won't improve performance.
- pkrumins 11y agoI'm not a React or Angular expert, but do you really put HTML inside of your JS code? It just bothers me too much. We spent years in early web days learning that code and templates should be separate, yet here we are putting HTML inside of code, which goes against years of practice. Can anyone share their professional thoughts about this?
- arethuza 11y agoIsn't that because it's really JSX? https://facebook.github.io/react/docs/jsx-in-depth.html https://facebook.github.io/react/docs/jsx-in-depth.html [NB Not that I know, just checking my own understanding].
- EvanPlaice 11y agoJSX is a HTML-like template language that gets preprocessed to actual HTML.
- Guillaume86 11y agoNo it's not getting preprocessed to actual HTML in React. Depending on the transform function, it can be turned to an object tree or a function calls tree (like in React) or actually HTML like you said but it's not a common use case AFAIK. It's not a text templating language like classic PHP, it's an object/function calls hierarchy DSL (more like vb.net XML literals). I think most people critisizing react for putting html in JS havn't tried it or don't remember why "html" in code was considered bad in the first place.
- EvanPlaice 11y agoRight. I was aiming for the 'simple' answer but should have said DOM instead of HTML. I'm also thinking in more of an Angular2 context as that's what I'm most familiar with.
- lucaspiller 11y agoYes, the JSX is compiled (or "transformed") to JavaScript which creates components internally in React: https://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&code=%20%20%3Csection%3E%0A%20%20%20%20%3Cdiv%3E%3Ch1%3ELatest%20posts%3C%2Fh1%3E%3C%2Fdiv%3E%0A%20%20%20%20%3Cdiv%3E%0A%20%20%20%20%20All%20my%20posts%0A%20%20%20%20%20%3Cimg%20src%3D%22http%3A%2F%2Fdreamatico.com%2Fdata_images%2Fkitten%2Fkitten-1.jpg%22%20alt%3D%22Kitten%22%20%2F%3E%0A%20%20%20%20%3C%2Fdiv%3E%0A%20%20%3C%2Fsection%3E https://babeljs.io/repl/#?experimental=true&evaluate=true&lo... I felt the same as OP when I first started using React, although it makes more sense now I've played with it, I'm still not sure about mixing concerns (code and view) in the same file. Especially when you start talking about CSS too... https://speakerdeck.com/vjeux/react-css-in-js https://speakerdeck.com/vjeux/react-css-in-js
- Ronsenshi 11y ago#3 Write functional components I'd say "Write functional components where it makes sense". For simple components that is a reasonable advise, however in cases when you need such methods as `componentDidUpdate` or generally any lifecycle methods - that won't do and you have to use classes.
- _asummers 11y agoNot a React guy, but why couldn't the component that updated broadcast that it did so? Or is that componentDidUpdate method a callback to the message I'm describing?
- lopatin 11y agoDepends on what kind of component just updated. If it's a low level text field, it probably shouldn't broadcast the change to anywhere else in the program. Instead it would invoke it's 'onChange' callback. This way, there are no extra dependencies for making the text field component work. The parent component always provides the onChange callback and takes action accordingly. However, if the component that just updated is high level, like an entire page or something, then it's reasonable to assume it's a one-off controller component and you should feel free to broadcast messages and couple the component with other parts of the program. https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.1na8fj54h https://medium.com/@dan_abramov/smart-and-dumb-components-7c...
- Ronsenshi 11y agoIn addition to what lopatin replied to you - sometimes your component have to subscribe to some window event - for example 'resize'. I'd say it is way better to handle this event attachment/removal within the component instead of inventing some convoluted system of events in the root container which broadcast changes. There's a number of situations when functional component just not enough.
- tzaman 11y agoI'v done an integration test example (no PhantomJS, just jsdom) if anyone is interested: https://gist.github.com/tomazzaman/790bc607eb7ca3fd347f https://gist.github.com/tomazzaman/790bc607eb7ca3fd347f
- k__ 11y agoI tried a different approach here: https://github.com/kay-is/react-from-zero https://github.com/kay-is/react-from-zero
- mythz 11y ago# 3. Write functional components Functional Components don't get Redux's connect performance optimizations which is a good reason to avoid them: https://github.com/rackt/redux/issues/1176#issuecomment-167015145 https://github.com/rackt/redux/issues/1176#issuecomment-1670...
- stickperson 11y agoI think Dan is making a different point. He's saying functional components are just like regular components in terms of speed. The author of this article is saying use functional components so it's clearer when a component needs to be split up.
- saidajigumi 11y agoI have to admit I find the author's insistence on defining a component as a function to be a big red herring. Instead, it feels like the presence of JSX outside of the component's render() method is the (potential) code smell. It doesn't help that several popular React & React Native tutorials out there, for understandable simplicity, opt to use "renderSubThing" methods. In the examples and in my own code so far, I mostly find those sub-render methods to be a proxy for "I don't want to break stride to make a new component, so I'll jam this stuff in a method and refactor later." That's great, so long as the refactor actually happens. (Hm, that'd be a great candidate for a vim refactoring plugin...)
- deleted 11y ago[deleted]
- lukesan 11y agoWhat really bothers me about React (and other frameworks) that without JS you do not see anything. No fallback. No progressive enhancement. Is this really the way to go? Did JS replace HTML/CSS as the backbone of websites/applications ?
- andrewingram 11y agoThis isn't strictly true. Though the workflow isn't ideal yet, it's perfectly possible to build a React project which is initially rendered on the server and then progressively enhanced. I've done it before, as have others. In fact, my single biggest criteria for any tech I add to my stack is that it doesn't get in the way of server-side rendering (the second biggest criteria is that it doesn't add significant weight to the client-side JavaScript payload).
- matt4077 11y agoThere are ways to render the output on the server, which helps search engines, first-page load times and Richard Stallman
- LeonM 11y ago+1 for the Stallman pun, so true
- tomjen3 11y agoIn the cases where react makes sense - where the users change data together or where new data is often enough generated on the server, yes. Try to make Trello work as well as it does today without javascript - ain't happening, you would be reloading every few seconds in case somebody else has made some changes. On e.g a newssite react doesn't make much sense though (except, possibly on the backend).
- todd3834 11y agoGreat article! As we have been on-boarding developers with React, we noticed that all of the boilerplate needed to get Babel, Webpack, Redux, and a testing environment (we use Mocha, Karma, and Chai) was simply too much for most people to handle while beginning something new. There are lots of boilerplate projects but telling someone new to fork a project on GitHub and start building an app from there was raising some eyebrows as well. That's not all, there are really amazing developer tools available for React development like the redux dev tools, and hot module replacement to name a couple. These tools are extremely helpful to beginners but a beginner is not going to enjoy the extra work of setting that up as well. Imagine if you were going to build an app with Rails and the instructions were to follow a tutorial that had you manually hook up active record, create your bootstrap files by hand, write your own code to rebuild the server ever time code changed… or even forking a boilerplate Rails project and going from there. I don't believe Rails would have become what it is today without the Rails CLI. What happens when the boilerplate changes? What if you find a XSS vulnerability in the boilerplate project that you used in your last 10 projects. Rails developers have identified and quickly patched several security vulnerabilities over the years. It's usually as easy as updating a gem file to patch your app. With the boilerplate approach, you would have to manually update all of your apps or try to merge the update from the project your forked. That isn't going to be fun at all. Finally, one of the coolest things you can do with React is server side rendering to build universal apps. At this point, even if you know exactly what you are doing, setting up a new app is going to give you way too much work just to get started. So you'll need to find a boilerplate with server side rendering and fork it. There are way more opportunities for security issues when you increased the surface area of your app's responsibilities. There will be updates to this boilerplate and you will have to merge them into all of your apps. I hope you like manually updating files and resolving merge conflicts on files you don't really understand… We set out to resolve these problems when we built GlueStick (https://github.com/TrueCar/gluestick/ https://github.com/TrueCar/gluestick/). It's a CLI that allows you to quickly generate new apps using all of the tools we like to use on React applications. You have generators for creating containers (smart components hooked up to redux), components, and reducers. Redux is set up out of the box. You have server side rendering out of the box. We also push as much of the boiler plate code into the GlueStick module as we can. This lets you easily get performace and security updates as well as new features by simply updating the node module. You also get a sane folder structure so that all of your apps built with this tool will be easy to navigate. We built this tool at TrueCar but we open sourced it. That means you can take it and make it your own, contribute back if you want to improve it and you can rest assured that it is backed by a big company that is heavily invested in seeing it succeed.
- tptacek 11y agoSomeone sell me on Webpack? We use Browserify for no other reason than that someone gave me a boilerplate Gulpfile that relied on it. What part of my life would actually get better if I took the 4 hours of my life I will never get back to make this switch? Thanks!
- stickperson 11y agoIf it works for you stick with it. I started with webpack for the same reason-- I wanted to use ES6 syntax, and a coworker had some boilerplate that did most of the work for me.
- keda 11y agoI found code splitting feature useful. It's insanely easy to lazy load partial script. https://webpack.github.io/docs/code-splitting.html https://webpack.github.io/docs/code-splitting.html
- Ambroos 11y agoI think Webpack has the monolith advantage here. It allows you to add things that would otherwise be immensely complex with ease because it can do a lot. You can have it handle bundle splitting and async loading of modules, image optimising and hashing, CSS/SASS/... processing, ... Since we started using Webpack where I work we've stopped using all other build tools. There's very little Webpack can't do, and the main advantage is that there's no need to hook things up to eachother since it's all part of the same system.
- tptacek 11y agoSo a big reason to use Webpack is that I can replace both Gulp and Browserify with it, and have one fewer component?
- stevejohnson 11y agoYes. Also, it will build faster and the configuration will probably be simpler. That's been my experience having used Browserify with Gulp and Grunt for 2 years and then switching.
- Keats 11y agoGood advices but I would add TypeScript as well
- jastanton 11y agoFantastic article, in the past 9 months you've hit on nearly all of my discoveries. Something I do now every time I create a new react app is to create a base class that extends React.Component that uses `PureRenderMixin`. When doing this I can prevent unnecessary renders from props changes. A killer of this would be passing an prop to a child that always changes its identity, like passing a function that calls `bind`, Because bind create a new method every time its call the identity always changes and the method will always be re-rendered. Knowing gotchas like these can help really speed up apps!
- baby 11y ago``` <section> <div><h1>Latest posts</h1></div> ``` isn't that div unnecessary?
- camjackson 11y agoIn the example as given, yes. In reality, it has `className="row"`. I stripped out all of the classes from the example code to make it easier to read.
- ktdrv 11y agoSome very good advice here but after reading through the list I had a familiar feeling. Functional, stateless, typed, Redux? Yep, that's Elm.
- meat_fist 11y agoFrom what I can tell, the only reason to use React/Redux over Elm is to have a more popular resume. This is not a criticism, just an observation.
- joseraul 11y agoHow about TypeScript/TSX? React's components and "views" are easy to type (and you get completion in your IDE) but I still have to find a convenient way to type an Immutable map where each key/value pair has a different type (the equivalent of a TypeScript object). Any idea?
- Retozi 11y agoyou can use the functional way of setState by passing a transaction function (state: State) => State . This allows for typed, immutable updates since the function gets passed a copy of the state. If you need an object (say to use it in something like Redux), you have to write a wrapper like so: https://gist.github.com/ebi/d186c4297c84d562aeae https://gist.github.com/ebi/d186c4297c84d562aeae
- marknutter 11y agoSo here we see the culmination of the great Frameworks vs. Libraries divide. Frameworks alleviate the need for the type of articles like the one linked here because they eliminate choice paralysis and imposter syndrome. Everyone is worried about whether or not they're doing things The Right Way™ and so they either blaze ahead and hit the same pitfalls everyone else does (and then write blog posts to warn others) or they hold off on adopting the tech until they are shown The Right Way™ by someone else. The truth is, libraries and frameworks both end up being equally complex to work with, precisely because the problem of building large applications is inherently difficult. It all comes down to personal preference: Are you the type of person who is more likely to believe you can do something better than everyone else, or are you the type who is more likely to defer to those you believe to be better than you? Are you decisive or do you agonize over the smallest choices? Do you feel a compelling need to understand how everything works, or are you willing to implicitly trust other people's systems? I find it amusing that people who gravitate toward smaller libraries like Backbone.js and React.js rail against frameworks like Ember or Angular for being overly complex, heavy, and "magical", and then proceed to cobble together a Rube-Goldberg-esque system of disparate dependencies to achieve the same goals. When React first started getting popular all you read about was how simple the API was and how it was Easy to Reason About™. Fast forward to today and you need to have working knowledge of WebPack, ES6, Redux, immutable.js, Babel, and a bevy of other dependencies to be aligned with the React ecosystem's ever-evolving best practices. The exact same thing happened with Backbone.js and it will probably happen again with the next shiny new view-model library to ride the hype train. It's important that I point out, however, that none of this is necessarily a bad thing. Smaller libraries like React.js and Backbone.js encourage a cavalcade of innovation from which awesome things like Redux are born. But let's not pretend that this doesn't result in a heckuva lot of churn for the average developer whose job is to simply get shit done.
- Retozi 11y agoI agree with your argument. I have seen people say on HN that 1 hour of setup to start a project is too much. If this is the case, React + stuff is really not the right thing for you. However, the React ecosystem is really not that complex. You can write clean, sizable apps with vanilla React. Then you might need a state management system like Redux. Its quite easy to roll out your own that fits your project and does not have all the pluggability whistles like Redux. All other things are really not needed for most people, and if you do, you are facing problems so large, evaluation of libraries is a small fraction of the effort. It's more the mindset of people "I'm missing something great" that drives them crazy and into framework fatigue. (OMG server-side rendering, falcor, relay, immutable.js arrgggh) Usually, you are missing something you don't need, otherwise you would be looking for it actively.