Hacker News new | comments | show | ask | jobs | submit login
Master these five concepts to master React (freecodecamp.com)
174 points by ziodave on Jan 11, 2017 | hide | past | web | favorite | 49 comments

Components and "higher-order component factory function". Waiting for "factory factories" and an iteration of Spring in Javascript.

I'm being a bit snide here since the Java community had to endure years of uninformed ridicule regarding the meta gymanstics required for component oriented programming.

I remember talking to a react or backbone (or whatever, it was the current 'thing') developer 1.5 years ago and giving a brief history of GUI toolkit frameworks before browsers. I swear, his eyes lit up like I was spilling occult secrets. Back to the future, par per course in this forgetful field.

[p.s. it's not just the browser side people. Many years ago I mentioned in a Go community group to take a look at the Servlet architecture (circa ~2000) and its minimal but powerful abstractions. I think it was yesterday that we had people cheering "context" in Go 1.8.]

You know, this information isn't really readily available to us user interface people. At least, it's not obvious where to go to read about it.

I would love a brief history of GUI programming concepts and patterns if you could point to one.

Smalltalk: http://www.create.ucsb.edu/~stp/PostScript/mvc.pdf

Fowler has a good overview of GUI architectures: https://martinfowler.com/eaaDev/uiArchs.html#HumbleView - note that this is at this point dated and does not cover the 'reactive' model.

He also recommends this survey: http://aspiringcraftsman.com/2007/08/25/interactive-applicat... (Haven't read it myself.)

Java also used to have a funky toy like thing in the beginning called Bongo (by a company called Marimba). It was a bit of a toy, but I found it an interesting, if flawed, take on scriptable GUIs. This is all I can dig up today: https://people.apache.org/~jim/NewArchitect/webtech/1997/10/... (If anyone here knows where I can download Bongo I'd hugely appreciate it. It was really fun to play with.)

I haven't seen anything about 'design-surface' & 'design-time' in context of Javascript frameworks yet but I have a feeling that will happen in due course. Can't dig up anything that is not .NET specific but it is a generally applicable idea for component based systems. Think GUI builders in visual studio or NetBeans. This is more of interest if you want to create your own framework.

Component models are a huge topic.

In the beginning (NATO, 1968): http://homepages.cs.ncl.ac.uk/brian.randell/NATO/nato1968.PD...

Hope this is of use to you.

There's quite a few "component playgrounds" out there for React. Storybook is one, Carte Blanche is another, and there's a few more besides that.

A quick search turned up this list of several tools along that line: https://github.com/xyc/til/tree/master/react/devtools

Good to know, thanks. I don't really follow the frontend tech anymore and obviously no longer buzzword compatible!

If only people listen, think and then decide whether a technology really works for them rather than trying to catch up to some "current" thing due to some sort of a FOMO experience!

On the other hand, you get to meet people all over the industry who were asked to deliver a simple Frontend app but built a new trending framework not because they had to solve a nontrivial problem but because they projected too much into the future that they thought that introducing some meta gymnastics will solve a probable UX scenario in the next 2-3 years down the product line!!!

Seems to be missing a 'not'

If anyone's interested in learning React, I keep a big list of links to high-quality tutorials and articles on React, Redux, and related topics, at https://github.com/markerikson/react-redux-links . Specifically intended to be a great starting point for anyone trying to learn the ecosystem, as well as a solid source of good info on more advanced topics.

Smart and dumb components are one of the reasons why I quickly jumped ship to Vue. It's too complicated and the starter apps make it worse. You get four level deep directory structures where each dir contains a single file of like five lines. It feels like knitting a castle.

Vue certainly has its own cruft, but it's at least somewhat simpler when it comes to how components compose.

The "container/presentational" component pattern is completely optional. If you want to write components that both fetch and display data, that's entirely up to you. Dan Abramov, who wrote the most widely referenced post discussing the topic ([0]), recently said that he somewhat regrets writing it because many people have assumed it's a strict rule that must be followed ([1]).

That said, it _is_ a very useful pattern, and can help with conceptual management of components. I have links to a number of additional articles discussing this pattern as part of my React/Redux links list ([2]).

[0] https://medium.com/@dan_abramov/smart-and-dumb-components-7c...

[1] https://twitter.com/dan_abramov/status/802569801906475008

[2] https://github.com/markerikson/react-redux-links/blob/master...

Thanks for the perspective. I guess I ran into this very thing.

React itself is actually a pretty simple library. The problem is that it's not the whole story, so you need other bits and pieces to put together a functional SPA. Ender redux, react-router, etc. And because React tries to explicitly not be so opinionated about what you should use, the way you learn about this stuff is not from the official tutorial, but from various blog posts.

There are also resources like this: https://github.com/kriasoft/react-starter-kit. On the surface it's great. But for my taste it's organized very poorly. You have all your reusable (NB: reusable != reused) components in one place, and all your pages in another. Each component consists of exactly 3 files that are 3 directory levels down. Pages (views? containers?) are in a separate directory structure where each page consists of 3 files that are 3 directory levels down. I guess if your SPA consists of hundreds of pages/views/containers with most components reused many times this makes sense. For my applications (low dozens of pages/views/containers) this seems like a huge overkill.

And don't get me started on the redux theory of all global state all the time, which actually seems to not be ideal for things like "I just want a more complex <select>", and you have a very scattered learning curve.

By contrast, Vue has a pretty sane slightly opinionated learning curve. Sure, there are a few things you need to figure out (XHR/Websockets + VueX + promises don't have a decent recipe in the docs), but overall it's much more coherent.

Please don't mistake the opinions of various boilerplate projects for authoritative info on how to use React (or Redux). The React team makes it a point to encourage people _not_ to use boilerplates as a learning tool, as they are almost always ridiculously over-engineered and over-configured, and therefore a source of confusion for someone who is trying to learn things.

You should use whatever file structure works best for you. "Folder-by-file-type" is common, as is "Folder-by-feature". My links list has a category discussing various project structures ([0]), but that's completely up to you.

Redux's global state has tradeoffs. There's a lot of value in keeping your data outside the component tree (passing data between components that aren't directly related, making hot reloading easier, etc), as well as benefits to having a lot of logic be centralized (consistent handling of API responses, logging of dispatched actions). The tradeoff is that some aspects do become more complicated.

However, it's also important to note that YOU ARE NOT REQUIRED TO KEEP EVERY LAST BIT OF DATA IN REDUX!!!!! People have over-interpreted the phrase "single source of truth", and game-of-telephoned that to mean "You _must_ keep _all_ data in Redux". No. NOT true. Per the relevant Redux FAQ entry ([1]):

> Using local component state is fine. As a developer, it is your job to determine what kinds of state make up your application, and where each piece of state should live. Find a balance that works for you, and go with it.

So, if it makes sense to keep a bunch of data for a <select> in the component that's rendering it, do so.

Finally, that "bits and pieces of info" aspect is exactly why I've put together my links list: to try to provide a single place that points a reasonably vetted selection of good info on React/Redux-related topics.

[0] https://github.com/markerikson/react-redux-links/blob/master...

[1] http://redux.js.org/docs/faq/OrganizingState.html#organizing...

> The React team makes it a point to encourage people _not_ to use boilerplates as a learning tool

What I would love to see is one of those over-engineered React+whatever boilerplate project that shows you, in a step-by-step form, showing the evolution from a simple project to the final boilerplate they have, and why it exists like that.

I have created a fairly-large project in Redux, but as I created it I know that it wasn't the "optimal" way of architecting it.

So, before starting another project, I tried starting from the "react-redux-starter-kit" project, and it was immediately over my head. I have to instantly grok how they're using the router, layouts, stores (I thought Redux didn't use stores...), modules... the source even has explicit references to the way WebPack is going to lazily load stuff, so I don't even know if I could use some other build system without breaking the source.

I'd love to see the same project laid out as a series of refactorings:

1. Here we have a really simple Redux project, the way a beginner might code it

2. They realize they need routes. Let's refactor the code to include the router

3. The realize it would be better putting the related-components in their own folders. Here's that refactorization.

... X. Look, your project now looks like the starter project!

Yep, that confusion is exactly the kind of thing I was talking about.

I've seen a few sample repos that try to demonstrate the kind of thing you're talking about. Skimming through my links list, these look relevant: https://github.com/verekia/js-stack-from-scratch and https://github.com/Jordaanm/hipster-boilerplate . I think those are a bit more oriented at the build tooling side and not so much the application side, but they're close.

Also, the "React Tutorials" and "Redux Tutorials" categories ([0], [1]) in my links list both have a subsection labeled "Project-Based Tutorials", which points to articles that do have a more "build something meaningful"-type approach as opposed to just "here's concepts A, B, and C".

To call out one specific example: I have been writing a tutorial series on my own blog, called "Practical Redux" ([2]). Rather than trying to teach the basics of React or Redux, it's intended to demonstrate a number of more intermediate and advanced concepts through building a sample app (one that's at least moderately more complex than yet another TodoMVC implementation). I'm not going to cover routing, because I've never done any client-side routing myself, but it _is_ kind of along the lines of what you're looking for. I describe the next piece I want to implement, link to the commit implementing that change, show some relevant diffs, and talk about the implementation. For example, I just published Part 6 today ([3]), which demonstrates the "connected list" pattern and then discusses a number of important Redux performance guidelines to be aware of.

[0] https://github.com/markerikson/react-redux-links/blob/master...

[1] https://github.com/markerikson/react-redux-links/blob/master...

[2] http://blog.isquaredsoftware.com/series/practical-redux

[3] http://blog.isquaredsoftware.com/2017/01/practical-redux-par...

Where exactly does the React team do that? That's the whole issue: the information is scattered and unless you are plugged into the community, you can't tell truth from opinion from best practice from someone's habit.

The official React tutorial is really basic and provides none of this guidance. The rest of the knowledge is scattered. You can discerne it eventually, but it takes lots of time, and often best practices change.

Are you basically concerned that the React docs don't teach a specific way to build a "complete, production-ready" application, with routing and all the bells and whistles?

Basically. As a newcomer to the platform, I was looking for at least one authoritative way to do things. There can certainly be more, but the fact that I have to seek out not "how to lay out a React app" but "who are the big names in the React community" makes for an unnecessary hurdle.

I am all for diversity of approaches, but there is no good starting point. So I spent days searching, comparing, etc.

Your list is great. It is not the only one. How do I know that yours is "correct"? The only answer is comparing which links show up frequently on various lists. That is so much more time consuming that having an official list or tutorial.

Yeah, there really is _no_ absolute "authoritative" way to do things in the React world. People use React to write complete SPAs with server rendering and client-side routing, and the latest build tools. People also use React to add a few widgets to existing static HTML, or with no build tools at all. They use it for developing web applications, native applications, and for really crazy stuff like creating sample-driven music, presentations, and driving hardware.

So, what would "authoritative" docs look like, given those wide varieties of use cases? The closest thing there is at the moment is the Create-React-App tool, which is deliberately opinionated about setting up a build tool system with certain behaviors, but is otherwise unopinionated about all other libraries and file structures you might choose to pull in.

The core React team is pretty small - currently like 7 people. They have to split their time between actually working on the library, and dealing with Facebook's internal needs. On top of that, the way Facebook uses React is going to be different than the way much of the community uses React, due to Facebook's unique and specific infrastructure.

For lists: yeah, there's some other useful lists out there. I actually point to them in the "Community Resources" category of my list. There was an issue discussing a possible new "Learning Resources" section for the React docs as part of the docs revamp ( https://github.com/facebook/react/pull/7117 ), which bogged down a bit due to concerns about endorsing specific libraries. There's currently an open issue regarding further additions to the docs that looks like a request for the community to contribute sections on specific topics ( https://github.com/facebook/react/issues/8060 ).

As for my own list: I put multiple hours into updating it every week, between reading articles, evaluating them, and categorizing them. I won't say I've read every word of every article, but I've definitely looked at each and every article in the list and determined that it's relevant and of good quality. Beyond that, I'd say that the nearly 6000 stars are a reasonable indicator that a lot of people are finding my list useful.

To be fair, Vue and Angular 1 and 2 all have pretty comprehensive getting started tutorials that don't teach you just a small part of the platform, but all of it. Sure, you can use Vue to just make a funny web component that's a part of a normal app, but that's not the main focus.

With the React ecosystem, it's basically equivalent to the Django template system having documentation, but the rest of the info being scattered across dozens of personal blogs.

The React team, being the face of the ecosystem, would do well to point newcomers to a list such as yours.

I don't know how you build your Vue apps but I think you should be using the same pattern there. So it's not really an argument against React.

"It feels like knitting a castle."

Google confirms this expression was coined here. Thank you!

I feel like I might be paraphrasing something but I can't remember where I heard it first or the original form.

It's from a Rich Hickey talk.

I'm loving Vue. I went from not writing javascript in 2 years (last stopping at Angular 1) to writing nice javascript app with clean codebase in a day. After a brief look at React and my experience with Angular 1, the same would take at least 2-3x longer with React or Angular.

I was annoyed by Javascript community churning out a new tool every week and deprecating everything every year. I lived through learning Ember and Angular1. Now, I just picked up Vue, a few crucial components from Vue MDL and wrote everything else in plain Javascript, CSS and a little bit Jquery. And just included scripts in my html. That's it - you get two innovations of Javascript world that make the biggest difference, two way data binding and components, at the least possible cost. It saves you from all the madness of https://hackernoon.com/how-it-feels-to-learn-javascript-in-2... , half of which will be likely deprecated in a year anyway.

This workflow is likely more productive for 95% of sites, unless you are relaly building a complex single page web app. It will be more resilient to the passage of time.

What did you use jQuery for?

Untiil there is a Vue Native. Vue.js will never be appealing to a lot of people.

It's in the works: > "Native Rendering The collaboration with Alibaba’s Weex project has made some substantial progress. Our first major goal — making Vue 2 the actual JavaScript runtime framework on top of Weex’s native rendering engine — has been completed in the latest 0.9.4 release. In 2017 there will be revamped documentations, better onboarding experience and API improvements based on feedback from the community and large-scale production use at Alibaba."


Agreed. ReactNative seems like a huge selling point.

Subjective content opinions aside, this article is short and to the point. Well written.

These and 3rd party integration, I think.

HOC aren't to bad to know either, if you want to end up with maintainable code.

shameless plug: https://github.com/kay-is/react-from-zero

Would you put "filling in the rest of the stack" as another finger of death? There doesn't seem to be good consensus on that bit.

Nor should there be a consensus. Back-end use cases are far more diverse than front-end use cases. Front-end frameworks should never prescribe the rest of your stack, IMHO.

"Rest of the stack" also includes things like build tools, Javascript testing framework, TypeScript, etc.

Fair point.

I'm not a front end expert...but the variety of choices around filling the stack for react seems broader than it was in the past.

It feels like there's more risk in making the wrong choice. I see lots of regrets around redux, for example, adding more complexity than initially wanted. Or, selecting a tool that becomes abandonware, etc.

Yes, there are a bunch of regrets about Redux, but I have the feeling it got better last year.

In 2015 we had countless Flux implementations and most of them have been abandoned. I did an app with Flummox, for example and switched to Redux later.

But now? Redux and MobX are basically the major players and you can still do small to medium sized apps without them.

Anyone who went thru the Angular debacle would certainly see it from a contrary point of view. Yes there is more risk of a particular piece of the stack being wrong and needing to be replaced but the risk is not a total rewrite of your app out of something like Angular 1. Rather it is a smaller effort such as moving your flux implementation or going from gulp to webpack. I think the modularity actually helps in long term support of an application, but you pay for it in up frot complexity and contextual understanding of all the pieces and how they bolt together.

React best practises question - At what level should event handlers be installed? At lowest level components or the highest level?

How are events in React supposed to be propagated from low level components to their parent components when the low level components should not have any knowledge of their parents?

By passing down callback functions as props. One of the basic patterns of React is that parents communicate to their children by passing down data as props, and they also pass down callback functions that a child can execute to communicate upwards.

There's a great article that describes various component communication patterns at http://andrewhfarmer.com/component-communication/ .

Thanks. Exactly what I was looking for.

Also, take a look at optional libraries such as redux (and its friends, e.g. redux-saga or redux-thunk). You don't have to use them, but when your codebase starts getting complicated with lots of callback, perhaps using those state management libraries would help.

You may want to have a read at Redux (http://redux.js.org) or any Flux type of container.

Basically, you don't propagate directly to your parent. In React there should be only one source of truth. So in your case, the event in a low level component should emit an action that will modify data in your Store/Container/Model. Then this change will be passed down (with the correct setup) as props to all of your components.

>React best practises question - At what level should event handlers be installed? At lowest level components or the highest level?

I personnally prefer when the handlers are close to the associated JSX. I doubt there is any requirement on this other than maintainability.

I don't think it is a good idea to drag Redux and Flux into the discussion when someone asks a basic question about React.

I think that depends, many would argue that a flux implementation is an easier way to reason about the problem set, thus their existence. Making someone aware that this is what flux implementation where designed (in part) to address, allows them to see the full scope of possible ways to accomplish their goal. I see nothing wrong with saying "hey that is why these guys built this library".

He was asking for best practices, certainly a sizable amount of developers would argue to use a flux implementation for that particular problem, as a best practice.

Still, you start with the basics, too many people are scared away from React because when someone asks a basic question about React, the answer typically goes something like this "oh, you better use Redux/Immutablejs/Redux-Saga/Babel/Webpack/etc". Usually without even addressing the actual problem.

In this particular case it would be totally OK if the answer included Redux. Because, like you said, it is relevant. But it should go something like "Pass event handlers from parent to child component. If you find a lot of components are merely passing through a lot of data and event handlers to child components without using it you should have a look at Redux".

You should have a look at acemarke's response and neurostimulants follow-up, together they answered this question perfectly.

You pass the event handler from the parent component to the child component as a prop.

Good article besides the nonsense about some of the react lifecycles being voodoo. You will use it if you program extensively.

> the component approach means that both HTML and JavaScript code live in the same file.

Something about this makes me want to facepalm and wonder why we bothered with separation of concerns, when React just undoes all of that.

That's exactly what I thought when I started using it.

But as I've got more used to it, I'm not sure it's really an issue, or at least doesn't have to be.

Firstly, JSX isn't really HTML. It's a bit of syntactic sugar around JavaScript "createElement" functions. If you don't want to have something that looks similar to HTML in your JS, you don't have to.

Secondly, if you want dynamically generated HTML, you're going to need some form of logic embedded in there somewhere (loops, conditionals etc). Most template languages end up with their own directives, like Angular 2's "ngFor". The React answer is to use standard JavaScript for that control.

And if you then want to separate out the non-display logic, you can use a combination of "smart" (pure JS logic) and "dumb" (JS/JSX display) components, and treat the JSX files as templates. "Separation of concerns" in this context isn't about not mixing code and markup, it's about not mixing business and display logic, and there's nothing in React that stops you doing that.

Applications are open for YC Summer 2018

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact