Hey folks! My name is Dan, and I work on the React team.
I really like the idea of semi-regular “beginner threads” where people can ask simple questions without getting judged. This seems like a great community so I thought: can we try this here? 🙂
We run a thread like this on Reddit but to be honest I'm finding Reddit hard to use and very impersonal so I don't hang out there much.
The rules are simple:
- One question per comment.
- The questions have to be about React.
- No question is too simple! Seriously, ask away, I don’t bite.
- Try to keep questions to a few paragraphs at most. If you need a code sample, put it in a gist or, better, a sandbox.
- Please reply to the questions too if you know the answer! I might not be able to reply to all of them although I’ll do my best for this thread.
Note this is an experiment. 😉 I don’t know if enough people here are React users, and if the format is a good fit for this website. If that’s not interesting to you folks that is fine too. Cheers!
Oldest comments (244)
When is it time to stop managing state at the component level and switch to something like Redux?
This is such a good question!
This is a tough one; I think it really depends on whether you consider your app a React app or a Redux app. It’s also kind of fluid: you might still use Redux-like reducers for implementing local state, like at the end of this article.
I might use Redux for:
Note that these use cases can be divided into:
setState()
sThe first use case really just means React doesn’t have a good way to do “global-ish” updates that directly update leaf nodes in the tree. So people use Redux to work around it, but it’s not really Redux per se that is useful to them, but the ability to broadcast updates. We plan to solve this with a new officially supported context API.
The second use case is also not as much about Redux, but about the
setState()
API. It is hard to keep a component with dozensetState()
s readable. Redux gives you a paradigm to split that logic into independent parts (reducers), but it’s not obvious to most people that you can apply the exact same approach to the React state. I think we can solve this by making React state API slightly different, and it’s something we plan to look at in the future.The third use case just means React doesn’t have a good solution for simple data fetching. You don’t usually want to keep it in the state because the data needs to be cached between mounting and unmounting components. So folks use Redux for this. We have some fun ideas about how to solve this with a first-class data fetching API in React, so watch that space.
Finally, when would I really prefer to use Redux? When its tradeoffs are useful. For example, for complex workflows where I want to reproduce bugs by “replaying” user actions. For distributed games that benefit from expressing everything as serializable actions. For extensible APIs where we want to let user hook into the update logic, like in Hyper. Etc. Where it really makes a difference.
The most important part is that the paradigm (actions and reducers) is not “bound” at all to Redux-the-library. You can take your reducers and use them to drive React local state in individual components, or vice versa.
Thanks so much for your response Dan! Your community efforts are impressive and tireless :)
Thanks for the honest recommendation Dan!!
Only when you share the same data with another component, Redux comes in.
But isn't that just a case where you make the container of both hold the state and pass it down. I suppose when it gets more complex than that you'd use Redux.
Personally, I'd say correct. When it feels wrong, that's when a state management comes in.
Do you work on React full-time? You seem so busy addressing people’s questions and complaints on Twitter 😅
Yeah, I work on React full-time. I suppose engaging with community can be considered a part of it although I mostly do it because I enjoy that, and it doesn’t take that much time to shoot a few tweets back.
How do you structure a container component in a React app that uses local state (no Redux)? Do you create a HOC for it?
I don’t quite understand the question. I think people take the distinction between “presentational” and “container” components waaaay too seriously. When I wrote an article about them I mentioned this is a pattern I noticed organically in a codebase, not a set of rules to follow.
If I were writing a component I wouldn’t think about whether it’s a “container” at all. I’d just write a component. It might use local state, or it might not. That doesn’t really matter to me. Later, I might split it into a few components, or I might actually “inline” it into a larger component if I realize it was extracted prematurely.
I would definitely not create HOCs except for very rare cases where a single HOC is useful across many many components. I would never create a HOC only for one component to use it.
Definitely check out github.com/acdlite/recompose/blob/... if you're into keeping everything an SFC, especially check out
withStateHandlers
.What is the best alternative of binding this in the constructor?
I tend to use class properties:
Note they're not standardized yet. But they're so widely used that if the syntax changes or proposal gets dropped, there's definitely going to be an automated migration path (i.e. a codemod).
Although it looks quite cool I'm really not at ease with class properties because of how they could be confusing, scope wise.
A fat-arrow function is supposed to be bound to the lexical scope in which it is defined and that is very much not the case here, which could lead to some confusions.
I don't know exactly where to stand :D
We’ve been using them in production at Facebook for about a year now, and haven’t seen much confusion in practice.
As a React newbie this is a game-changer for me. No more headaches with debugging just because I forgot to bind this to functions in the constructor!
Can't believe how old this comment is now! I still check it all the time for syntax lol - It's literally become it's own google search for me! Thanks for the (probably)10+ times this has helped!
i go for following
When we use state and lifecycle methods, the component identity becomes important. On a form with two buttons, two instances of a
Button
component are independent because each has its own state, and may mount, update, or unmount at different times.For better or worse, classes are how the vast majority of people think of “identity” in JavaScript (and many other languages). You can design your own bespoke system that creates objects through factories, uses prototypical inheritance directly and whatnot, but you’ll most likely end up with something that feels a lot like using classes. Except that it’s a dialect nobody else is familiar with so you have to educate your users about your pseudo-class system (and maintain it). This is basically why went away from the
createClass()
helper. We’re in a business of UI libraries, not class abstractions. Sebastian goes into this here: youtu.be/4anAwXYqLG8?t=21m33s.We might not want to keep using classes forever though. They have their own problems (and I don’t mean stylistic ones). Our two big directions to explore in 2018 are async rendering and compilation. Classes make both of them harder because you can put any field on the
this
instance and mutate it at any given time. For async rendering, this is a problem because changes can be “stashed” and “reapplied” later (much like Git) but React only knows what to do withprops
andstate
rather than arbitrary objects you put on the instance. For compilation, this is a problem because classes are too hard to “fold” statically because you can just do too many things in a class.So, considering these real issues, we might introduce a different, more functional API for components in the future. However, it is important that it will be informed by actual problems we experience with classes, and not just a stylistic or dogmatic preference.
Oooh acync rendering and compilation both seem exciting.
How does the React team work? Are you split up into multiple small teams that focus on a certain area? Do you have project/product managers? Who decides what you will be working on? Does the React team use Scrum?
By the way, really appreciate the time you take for answering questions and sharing your knowledge :)
The “React core” team takes care of the React repository and how it is used at Facebook. It currently consists of:
There are other teams that work on React Native, Relay, Jest, and other projects. We often chat with them but don’t work directly together.
Yes, Sophie took over team management from Tom Occhino in the second half of this year. The manager’s job is to sit in the boring meetings with higher-ups so we don’t have to (at least that’s how I imagine it 😄), help with planning, remove roadblocks, and enable people on the team to do their best work.
Our main goal is to help developers create great apps. We have brainstorming sessions two times in a year where we consider what seems like most impactful things to work on next. They are informed by the challenges we see at FB and other companies using React, and by our own intuition. When we agree on the directions, there’s generally quite a bit of wiggle room on the specifics. At Facebook engineers are trusted to make their own decisions about what they think is valuable to do.
I don’t really know what Scrum is. We have a weekly hour-long team meeting where everyone gives brief status updates and then discuss anything that somebody on the team put on the agenda (e.g. some API decision, bug, etc). Everybody also has weekly 1:1s with their manager that last for 30 minutes. Apart from that, we don’t really have a lot of process around anything. Sometimes we do more specific meetings around a particular topic with folks from other teams at Facebook or our open source contributors.
Weekly 1:1s? And I thought my fortnightly 1:1s were too frequent 😂. Can you explain at a high level what kind of things you would talk about at your 1:1s?
I must use this list for my next 1:1. Thanks for answering and enjoy the holidays!
Another question I had about the React team dynamic: Are you all at the same office location, or are some of you working remote?
Most of the team works together in Menlo Park (USA), but me and Dominic work from the London office (UK). We don’t really have remote positions at Facebook, but we do occasionally work from home if we don’t have any meetings.
Hello Dan and the rest of the Dev.to community!!
I am new to react and started with it last month. I searched for react tutorials and docs and related articles over the internet and found you contributing directly or indirectly somehow at all the great places I found.
Me and many more people appreciate your efforts! Thanks a lot and enjoy your holidays! :-)
Hey Dan, thanks a lot for doing this!
Are there any resources you would personally use if you were a standard React user who's trying to learn the library in-depth?
Depends on what aspect of React you're trying to learn. There's differences between trying to learn the core APIs, some of the flexible ways you can compose components together, or how React works internally.
The official React docs are the best place to start. After that, my React/Redux links list points to many good tutorials and articles to help learn React further. In particular, you might want to check out the React Component Patterns, React Component Composition, and React Architecture sections.
Agreed with that. There's also good community content here: reactjs.org/community/courses.html
Welcome Dan, definitely a lot of React folks happy to have you around.
This definitely jives with the reason we're here in the first place.
This is great. We'll be following this post for cues on how to build on this sort of post and any feedback from you or anyone is really appreciated.
Now for a question: What are your thoughts on Preact, how does the React team/community interact with spinoff projects like this?
I think it’s cool that people want to stay within the React paradigm even if their tradeoffs don’t match ours.
At Facebook, we typically use React for applications that are truly dynamic and need to scale well with the application size. We don’t use it for stuff like landing pages or extremely thin apps. So in our case the difference between 3 and 30 kB gzipped is less pronounced because the vast majority of the code comes from the application itself.
For our use cases, supporting older browsers consistently and having great runtime performance is more important. We're also still working on React, and as we enrich its capabilities we're hoping to bring down the repetitive code in the product (e.g. for data fetching). We think will be more impactful because, unlike the library, the product code keeps growing over time.
We don't really interact with these projects as much, but we hope they continue to be useful to the folks who rely on them, and will happily welcome these users back if they decide React better answers their tradeoffs later. 🙂
Hey Dan, thanks for doing this. What would you say is the latest best practice for approaching CSS/styling in React?
Hey! I don’t think there any “best practices” because the field is still evolving and there are many unsolved problems. If I were to create a project I’d probably still use plain CSS 😅 Facebook uses something similar to CSS modules (but with a different syntax) and that works okay-ish too. In side projects I’ve enjoyed using glamor but I don’t really have any opinions there.
I'm not a Dan Abramov :D But still, react is lightweight library so I'm not sure that they will add any "CSS-in-JS thing" to it that is more complex than inline-styles that they have now.
About best practices now and what community is fascinated about is surely CSS-in-JS libraries.
Such as
styled-components
,jss
,glamorous
.They have automated out all styles isolation problems keeping the ability to work with 3rd party CSS styled components.
At the end, we have:
And many other things like discoverability of usage, modularization of the styles, so you don't have any unnecessary styling applied to the page, dead simple theming support, lot's of reusable functions, mixins, shortcuts and everything you can imagine cause it's just JS.
You can analyze it using way more tooling than CSS have, you can programmatically do tons of stuff etc.
If you want an example of usage of
styled-components
which is the most popular solution, for now, go ahead here.codesandbox.io/s/21nx9pw8jr
I highly recommend
styled-components
.About more traditional things, well, postcss with CSS modules and cssnext preset is a nice thing for old-fashioned people, but is way-way-way-way weaker than
styled-components
and jss and glamorous in terms of natural use with React and component way of doing things.Liana, I don't know if this could be considered a "latest best practice", but it is something I've started doing for my own projects, which is to import CSS files as modules
import "./component-style.css"
inside the component file, then use Webpack to compile it.You can avoid errors during testing using ignore-css module.
If you research a bit there are very interesting articles on the topic, and it has helped me to keep my CSS modular and clean.
You can even keep your CSS file close to your component.js and component.test.js files in the same folder, which for me at least is very practical when working on any particular component.
Hope it helps!
Or you can just use
styled-components
and all that will be very natural with zero dead CSS code :PI've done a lot of Web UI work in the past, but have yet to work with React. I'm familiar with the basics, but one question I haven't yet answered for myself is the Why of React.
So, in a nutshell, what would you say is the main problem that React is trying to solve?
I know that could get fairly philosophical, but I'm really looking for something just a level or two deeper than "It's better than X!"
Thanks!
Same problem that functions are trying to solve in regular programming languages, but applied to UI. Does this help? (Let me know if it’s too brief and I can expand. I was going for “a-ha” but maybe this just confused you more.)
Actually, if I understand what you're getting at, that helps a lot. I can definitely see the value in making the mental model of assembling a large, dynamic UI be similar to that of assembling a "normal" (for lack of a better word) program.
Thanks!
Yep, that’s about it.
The interesting difference from “normal functions” is that the “React functions” (we call them “components”) can be stateful. For example a
Checkbox
component doesn’t just “return” something unlike a normal function, but can be toggled on and off. We call this “state”.The state in "React functions" (components) resembles C++'s local variables, defined inside functions using the
static
keyword. Such variables keep their value between function calls. If something similar existed in JS, you would be closer to being able to use functions to implement components exclusively, and avoid downsides of using classes that give you a hard time working on async rendering and compilation.Also unfamiliar with React and have read some stuff about it and been largely unsure and this summary is seriously golden in my book and legit seals it on me checking it out more--because that's an explanation that makes total sense.
As someone that comes from a Vue background, conditionally rendering things in React look a bit cumbersome to me. In Vue, I just use a
v-if
directive in the element and I'm good to go, but I'm react I see myself constantly doing stuff like using the ternary operator{ obj.attr ? <Stuff></Stuff> : null }
.Is there a better solution? Am I approaching things in the wrong way, maybe?
React seems easier than Vue for conditional rendering in my opinion, in the end it's just javascript and you can do it in many different ways!
I completely agree with Camilo.
The main problem for me why Angular and Vue is quite meh is because you need to learn another domain specific language. So you need to know some gotchas here and there, some limitations etc. So at the end of the day, maybe ternaries starts to become cumbersome (than you probably need to decompose component to smaller pieces to abstract this away) but at least you surely 100% know how it works.
About make it more beautiful, you can use just shortcut like
{obj.attr && <Stuff/>}
Or just use some simple high-order-component, or decompose things and move this clutter to the component itself.
This is one of the big philosophical and opinion differences between people who prefer Angular/Ember/Vue and people who prefer React.
React users generally point to the phrase "it's just Javascript" as a positive thing. Flow control and conditional rendering uses normal JS
if
statements and conditions, rendering lists is normal JS loops and array methods, and so on. There's no special templating mini-languages needed. Render methods also give you the full power of JS to write whatever logic you need.People who prefer template-based rendering usually emphasize things like the ability to have designers edit HTML directly, and finding templates easier to read.
Both are valid approaches, and it really is a dividing line based on your own preferences. I personally am very happy with using JS-based rendering logic, and have no interest in using templates, but YMMV.
I see why you might find this cumbersome although to be honest I got used to it pretty quick and it stopped being a problem for me a few months into React.
In fact I found the ability to use any JS constructs liberating because as soon as the condition got more complicated I could extract it in a variable, a function call, a
switch
statement, an object property lookup, or any other valid JS code.That said we do have some ideas about allowing something like
to work (see this proposal).
Interesting... Yeah, I can totally see how abstracting complex conditions into a variable can be useful. I guess it makes a lot of sense - it's all just javascript in the end.
Thanks for the answer!
Cam you explain to me the component lifecycle?
When something is rendered for the first time, the component "mounts". This is when
componentDidMount
fires.When something of the same type is rendered in the same place again, the existing component "updates". This is when
componentDidUpdate
fires.Finally, when component is being removed (because the parent no longer renders it),
componentWillUnmount
fires.There are a few other lifecycles but they're more exotic and much less common. We're also probably going to change some of them so I recommend not spending too much time on learning those.
Not sure if it's still up-to-date, but I used to refer to this diagram: d.sb/reactlifecycle
I want to implement offline support on my React project I built with the YouTube API. Do you have any suggestions on how I can get started with this implementation?
You might find something like this helpful: developers.google.com/web/tools/wo...
You could also use Create React App which by default lets your app work offline: github.com/facebookincubator/creat...
Okay and if I may ask will Workbox be able to cache the fetched videos from the YouTube API but only rerender the app when the API makes a new call for another video?
I don’t know but I’d be very surprised if it could. Workbox is for caching your own assets, not downloaded assets. I don’t know if it’s possible to cache videos from YouTube but my guess would be no.
Try to post this question on the Google Product forums or in Twitter. I had questions about Google OAuth APIs and got very fast response via Twitter and e-mail...
Hey Dan! I have followed your work a lot and have looked to your ideas and suggestions on how to approach certain problems in React. Thanks a ton for all your effort in the React community. A lot of people benefit from you.
Recently I had a bit of a problem using a React parent container which had two sibling containers in it. One of the use cases I had was, when one of those child component changes, the other sibling had to re-render. I was able to manage this but it looked really cumbersome. Is there a good practice or suggestion on how to efficiently manage this?
You can make one of the sibling components descend from
React.PureComponent
. This gives you a nice opportunity to “skip” updates when state and props are shallowly equal. See also: reactjs.org/docs/optimizing-perfor...Do you have any plans for using ReasonML in react development any time soon?
If you mean in development of React itself, I don’t really see it happening over the next few years. It significantly raises the contribution barrier but being able to compile React itself into native code is not that valuable IMO. And a solid type system doesn’t really buy us that much with a relatively small React codebase. However, it may be valuable for something like WebAssembly in the future. So I don’t know.
If you mean for development of products with Reason, we’re already using React for Messenger. I don’t know if it will be used more widely in the future, we’ll see!