React Beginner Question Thread ⚛

Dan Abramov on December 24, 2017

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 q... [Read Full]
markdown guide
 

Hello Dan.

I'm a React learner and right now I've digested only the basic stuff. How should we approach to shouldComponentUpdate? Some people, including my friends who have more experience than me, say "consider using it always" since without using it there is so much unnecessary render around and that slows the application. Even one of my friends showed me a real use case of it and his application slows down very much without using it.

The official documentation says "The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior."

Should not I use it?
Should I use it when necessary? For example after measuring the performance?
Should I design my application wisely so every render does not slows it down dramatically then shouldComponentUpdate will be unnecessary?

I've read some suggestions but I also want to hear yours.

Thanks.

 

In my personal experience you should use it only when it's necessary. I found using it almost always a solution to another slow thing. Let me give you a real example:

In a project I worked there was a list of comments (similar to this same list), it rendered 10 comments with all of his sub comments and then using infinite scroll it was loading more comments (and sub comments), but the render was too slow, specially after I loaded more pages of comments (the second time I loaded more comments the page took 10 seconds to update, in that time it was completely blocked).
My first attempt was implement shouldComponentUpdate for each component, and it worked, but after deploying that I investigated more and discovered the code was applying highlight.js to the whole document after each component was rendered and in a sync way, this was causing the super slow render.
So I could have used shouldComponentUpdate and call it a day, but if I did that I was never going to found the real issue.

React is already trying to update the DOM as little as possible, so you don't really need to care about your render method being called many times because it should be fast enough. Also implementing shouldComponentUpdate in any component could cause some unexpected issues like this:

You have a component A rendering a component B, both components are stateful. If A is a PureComponent (or manually implement shouldComponentUpdate) and B change it own state since A is not being updated (its state and props didn't changed) it's going to say that it does not need to update, which cause B not to update (because the React's rendered is going to stop traversing the internal component tree of A).

Another possible issue of using shouldComponentUpdate always is that you're adding more logic which need to be run every time something update, e.g. if your render method take let's say 100ms to render and now you need to run another 100ms logic inside shouldComponentUpdate to check if it should render it means you're still going to wait 100ms always and if the component needs to update it going to take 200ms to do it. Now imagine this everywhere.

tl;dr: only use shouldComponentUpdate if you measure you really need it and not always.

 

^ I agree with this. I’d also note you probably want to use PureComponent when you optimize instead of manually writing shouldComponentUpdate. Then verify with React DevTools (“highlight updates” checkbox) and Performance tab in Chrome (“User Timing” section) that the components don’t re-render anymore. Because the worst thing you can do is to add a shouldComponentUpdate but not verify that it actually bails out when expected.

Thank you for your answer Dan. I am definitely going to consider using PureComponent instead of shouldComponentUpdate, if I need it of course.

 

I'm provably misunderstanding something when you said:

You have a component A rendering a component B, both components are stateful. If A is a PureComponent (or manually implement shouldComponentUpdate) and B change it own state since A is not being updated (its state and props didn't changed) it's going to say that it does not need to update, which cause B not to update (because the React's rendered is going to stop traversing the internal component tree of A).

Why should B not update? Is this what you meant? codesandbox.io/s/ol4zllpj19

 

Thank you for this good, detailed answer. So, I won't consider using it unless I'm certain of it makes the application better. Using like a very sharp knife, use it only when necessary :)

 

Dan, please clarify on the use cases of PureComponent other than stateless components. My understanding of PureComponent is that if misused, will slow down the application rather than making it faster. Since PureComponent will diff the changes before rerender.

 

Use PureComponent when you have performance issues and have determined that a specific component was re-rendering too often, but its props and/or state are shallowly equal.

reactjs.org/docs/optimizing-perfor...

 

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.

 

Here goes another one: what would you recommend as initial steps to participate in React as open-source collaborator?

Thanks again!

 

First, just use React 🙂 You will notice bugs, pain points, etc.

Then, I encourage you to try helping people in the Issues section. A lot of those are just support requests or misunderstandings, but some are legitimate bugs. Even helping verify those bugs and creating minimal reproducing examples is a hugely valuable contribution. Answering React questions on StackOverflow is also a great contribution and grows your experience with the library.

Finally, keep track of the "good first issue" label in the repository. We use them to tag issues that we think are good entry points into helping with React.

I hope it helps!

 
 

Could be a silly question since I have not used React much. Recently i saw a code base using react and could not find much of unit testing. But there are lot of "snapshot" testing with Jest. I think that Jest internally compare a previously generated text output with current and break the test if it is different. But i don't think "snapshot" tests can totally replace unit testing since "snapshot" tests can't really test interactions isn't it?

Also how "snapshot" tests fit in to TDD?

Thanks.

 

Snapshot tests aren’t meant to replace unit testing. They’re complementary. I suggest using snapshot tests for cases where otherwise you wouldn’t have written any tests at all.

People have different opinions about how much unit testing is useful for components. When I was building products with React I didn’t write unit tests for components at all because they were changing too often, and adjusting tests all the time would slow me down. And if some logic is complex enough to be worth testing I would extract it out of the component anyway. I also definitely didn’t use TDD for components (my personal opinion is that TDD isn’t very useful for UI code in general).

But this is tradeoff is different for every team. Some teams find more value in unit testing components. You definitely can do this with React—either with react-test-renderer or enzyme. It is up to you to decide how to balance unit tests with integration and snapshot tests in your app.

 

Thanks for the rapid response in the Christmas day! Another question regarding HOC. How HOC is different from decorator design pattern?

I guess it’s a React-specific variation on it?

Probably :) but I can't really confirm since I have not used HOC in depth.

 

But i don't think "snapshot" tests can totally replace unit testing since "snapshot" tests can't really test interactions isn't it?

A snapshot is simply a different way of performing an assertion, instead of using expect(...).toBe(...). You can write any type of test using snapshots.

 

That’s a great point, you actually can test interactions with multiple snapshots.

 

I'm a beginner in JS world . So What are the concepts that I should know to learn and use react easily .

Many of my friends said react is not actually a beginner friendly one . So they asked me to try angular or polymer etc...

Is that so ?

 

React is a very lean library that one can easily learn. As a developer worked with Angular JS and Angular>2 before, I felt react is less opinionated, fun and, easy to learn. The react's component based development is far more well thought than the AngularJS's two way data binding & controllers. Angular >2 is a very opinionated framework that takes a long time to master.

Beginners who try React for the first time easily gets scared by the diverse tutorials out there. They use things like JSX, ES6, Webpack, Redux which annoys beginners and creates a pseudo humongous learning curve. Instead, you(a beginner) can straight forward include react.js and react-dom.js in your HTML and start creating components(like Angular JS).

Read this book, if you have a chance:
shop.oreilly.com/product/063692004...

It teaches you react from plain JavaScript's view. After reading this, read the official docs and everything makes sense to you.
reactjs.org/docs/hello-world.html

For more tutorials on React, visit this.
github.com/markerikson/react-redux...

Note:
First, learn JavaScript well. If you are good at JS, understanding a library is an easy thing. Reverse may not be true.

 

I think it’s very subjective. I know a lot of people who learned JavaScript through learning React. I think the main difference is that React embraces JavaScript instead of trying to hide it from you. So you need to get comfortable with the language. The upside is you don’t just learn a library, but actually learn the language you’re working with 🙂

I don’t think you need to know much to get started. To feel comfortable you’ll want to understand JS syntax and concepts (functions, classes, binding).

Really, the only sure way to know is to start going though our docs (reactjs.org/docs/hello-world.html) and/or the tutorial (reactjs.org/tutorial/tutorial.html). Try it and see!

 

Agree with Dan (not that you need me to). React is more like Javascript than Angular (I've used both) and most other frameworks, it really does embrace Javascript. I also feel like React embraces functional programming which is a good way to build good habits.

I dove into React as a beginner and found it much more beginner-friendly than most other frameworks or libraries. Beginner friendly doesn't mean it does a lot of the lifting for you like other frameworks that might do more 'under the hood' (although it does quite a bit).

 

Is there any particular criteria to prefer class components vs functional components?

I've read many threads arguing about this, in many cases discouraging the use of ES6 classes in general (google "Eric Elliot class"). At least for me is a bit troubling since there are a lot of examples and documentation written using classes.

I have experienced some of the pitfalls of using class in other contexts outside React, although I do not discard these problems being a result of amateur coding skills on my part. Yet similar experiences are shared by more experienced developers.

I would like to hear your thoughts about this, and what is the position of the React team on this topic.

Thanks!

EDIT: Reading below I see that you already answered a very similar question, anyway I leave this one in case there is anything else you would like to add. Apologies!

 

The one thing I encourage you to avoid is inheritance hierarchies. I think classes are okay as a form of organizing code, but work really poorly as a way to reuse the implementation through inheritance. I wrote about this here.

If you just inherit from React.Component or React.PureComponent there’s nothing wrong about using classes. Certainly, they can be unnecessary if your component doesn’t have any state or lifecycle. In this case a functional component would use a tiny bit less memory. However, it is annoying to convert them back and forth when you want to add state and/or lifecycles later 🙂. So that’s really up to you—it doesn’t matter that much either way.

TLDR: don’t create your own React base component classes and hierarchies.

 

One notable difference between functional components and class components is that refs (references to underlying DOM elements) can't be used with functional components - has forced me to use a class a few times, even when the component has no state/lifecycle.

A small price to pay for a great library - awesome work Dan!

 

Hey Dan, what do you think about mobx and mobx-state-tree? As state management solutions. Actually I knew about mobx because you tweeted about it, but not sure if you are familiar with mobx-state-tree.

Thanks for all your hard work and patience to answer so many questions in so many places

 

I think it’s great that people find them useful! Personally I’m not a fan of APIs relying on mutability because they make certain fundamental problems harder. For example we’ll need to work with MobX to figure out how to keep them compatible with async rendering in future React versions. It’s probably solvable but mutability makes such problems harder.

I’m also not a fan of wrapping real JS objects and arrays into shims that pretend to be them. I understand why MobX does this but I’ve always considered the ability to work with “raw” objects one or the biggest strengths of React, and I don’t want to give that up.

As for mobx-state-tree, I haven’t looked much at it so I can’t really say. The “fluent” API style is offputting to me but that’s just a knee-jerk reaction so I may have missed important benefits behind it.

 

Is there a set of libraries that are recommended for people once they finish the official React tutorial?

I'm not talking Redux, but maybe React-Form, that sort of thing?

Once I know what I'm doing and start doing small PoCs and move from lear-how-this-works to see-how-productive-it-can-be, I'm not sure where to just go with React and maybe native browser promises / fetch / forms etc, or there're de-facto options that can speed me up and everyone is using, and I just miss on them because I don't know what I don't know.

 

I don’t know 🙃

When I started with the React ecosystem most of these libraries didn’t exist in the first place so I had to write my own components from scratch. That’s the best way to learn too.

For forms, I’ve heard people rave about github.com/jaredpalmer/formik so maybe I’d try that. For routing, I’d use React Router. As for other purposes, I’d probably start by trying to write my own, and if it takes longer than I want, picking something with the closest API to the one I imagined.

 

Hi, Dan!

Really nice of you posting this thread. Great questions, great answers.

One question from me:

Any plans on creating a router or approving some of the existing routers as the "React Core Team approved router"? Seems like this is painful part of the existing React ecosystem.

 

I think we’ve been fairly open about liking React Router 4 🙂 It’s not perfect for every situation but I’d recommend it as a default choice.

 
 
 

Some internal teams use Redux, I don't think there's any public-facing Facebook pages that use it though. Most internal apps use FluxReduceStore from facebook.github.io/flux/docs/flux-..., which is similar-ish.

 

When is it time to stop managing state at the component level and switch to something like Redux?

 

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:

  • Data caches (note: there might be better solutions than Redux for this)
  • Things that are like “global variables” (e.g. authentication)
  • Things that have very complex update logic (e.g. a multimedia post editor)
  • Things that many distant components care about
  • In general, when the state tree shape is too different from the UI tree shape

Note that these use cases can be divided into:

  • Variables that are annoying to explicitly pass down the React tree
  • Update logic that is too complex to express with a bunch of setState()s
  • Data fetching and caching

The 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 dozen setState()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 :)

 
 
 

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.

 

Welcome Dan, definitely a lot of React folks happy to have you around.

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.

This definitely jives with the reason we're here in the first place.

Note this is an experiment.

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?

 

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. 🙂

 

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 :)

 

Are you split up into multiple small teams that focus on a certain area?

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.

Do you have project/product managers?

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.

Who decides what you will be working on?

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.

Does the React team use Scrum?

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?

  • What I’m working on
  • What I’m struggling with
  • What’s worrying me
  • What others are doing
  • Technical roadblocks, decisions, planning
  • Just chatting

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! :-)

 

What is the best alternative of binding this in the constructor?

 

I tend to use class properties:

class Button extends React.Component {
  handleClick = (e) => {
    // no binding
  }
  render() {
    return <button onClick={this.handleClick}>hi</button>;
  }
}

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

  1. bind only if you need it in children Component or Event
  2. Re-using same function ? try to use "Call" if that becomes complex then use bind.
 

Hey Dan, thanks for doing this. What would you say is the latest best practice for approaching CSS/styling in React?

 

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 :P

 

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:

  • perfect props dependent styling
  • isolation
  • styles encapsulation within the component

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.

 

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.

 

What characteristics (if any) do you think describe apps for which React isn't suitable? I'm guessing particularly small/simple apps wouldn't benefit, but does anything else come to mind?

 
  • Apps where hundreds of things on the page constantly update at the same time over a very small interval. For example stock trading apps. You don’t need the expressiveness provided by React for most such apps, and optimized templates (e.g. Angular AOT, Glimmer) will be faster for these use cases because they skip the component abstraction.

  • Primarily static websites. However that really depends on how you use React. For example we actually do find it very helpful for the (mostly static) reactjs.org website but we can do this because we use it through Gatsby which generates a static website from React components. This is very different from just adding using client-rendered React components for everything.

  • Embedded widgets. By nature they’re supposed to be as tiny as possible, and there isn’t much of an “application” in them anyway. I guess you could use something like Preact but perhaps plain JS or something like Svelte would still be best for these cases.

 

Is there a shift to make the React API more functional and less class-based? Why are classes a good choice for current lifecycle and state implementation?

 

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 with props and state 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.

 

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.

 
 

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.

 

I'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.)

 

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.

 

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.

 

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!

 

How do you bind Redux to React so the component would be updated when the Redux store change?

 

You use the react-redux utility with the mapStateToProps function, which does the thing as it's called, so that whenever the state (of the store) changes, the props changes as well. And it triggers the re-render of react components.

 

Thanks, Chang! I think I wasn't clear enough, I'm sorry! I meant the details of the implementation of such patterns.

Internally React Redux works by calling store.subscribe() when the component mounts. Every time the Redux store changes, the subscription callback fires. Inside it, React Redux calls React setState() by taking Redux store state and passing it through mapStateToProps().

Here’s a simple version: gist.github.com/gaearon/1d19088790...

Thank you so much! That's exactly what I wanted to know :D

Thanks Dan, the code example is really helpful. Also I found your video talk about react-redux very inspiring and straight-forward as well. For those who are interested, you can go to
youtube.com/watch?v=VJ38wSFbM3A. <3

 

For example I am working on a white-label product. And one component should look different for different environments. CSS and HTML also may differ. How would be a right way to make, kind of, interface for a component, and use a specific implementation for a environment.
I tried to make something like this, it seems to work. But is this the right way?

app.js
MyCmp/
  index.js
  env1.js
  env2.js
  ...

// index.js
const MyCmp = require(`./${process.env.MY_ENV}`)
export default MyCmp

// app.js
import MyCmp from './MyCmp'

process.env.MY_ENV gets assigned depending on env.

 

It's a pretty abstract question. It's not clear what you mean by "environments", what actually gets deployed, whether there is any common code (and if there is, what differs between environments). It would help to see a more specific (small) example.

 

When devloping a white-label product, and have more customers with their own brand books. You want to make UI to look different for each one. And sometimes just CSS does not help. You need to have different markup so component could look different for each customer. I know it's pretty abstract :)

github.com/iamandrewluca/white-lab...

Now if I change REACT_APP_CUSTOMER in .env file I get different src/components/customer

Why not export a component that takes props? In your example, <Customer name="Dan" /> or <Customer name="Andrew" />. Then you can have different apps render the same component with different props.

Of course in practice you'd have more props, but you can also pass a whole object with them, e.g. <Customer brandData={{name: 'Andrew', color: 'red'}} />. If it’s too cumbersome to pass it down the tree to every component you can also use context for this.

The reason I dislike your solution is that you end up bundling all variations for every single deployment. So your bundle for a baby powder brand would also contain all the strings you use for a vodka brand. Not great.

Actually I looked into compiled sources and is not bundling all variations.
Thanks for your reply!

Good to know! I guess webpack is smart enough to do the replacement earlier :-). This is still not a great future-proof approach because it relies on requires whereas the ecosystem has been moving to ES modules. It’s also much harder for any other tools to understand what’s going on in your modules.

 

Not quite relevant, but I'd like to share some experience on that because I believe this kind of problems is quite rare.

When my team was building a white-label product (not entirely in React and no variations in component behavior and HTML markup, mostly styles and texts in different languages, texts included HTML in a few places), we made a build system that spits out separate bundles for each "partner" and an app loader that loads the respective bundle given the "partner" identifier in runtime.

We split the bundled code into the core bundle which contained all the component implementations and the core component styles, a "partner" style bundle which included partner style overrides (we relied on CSS cascade to apply the overrides), and a messages bundle which included the translations compiled for the "partner" from the base and the overrides during the build.

This happened before the CSS modules came into play, so this might not be the best possible implementation, but it works for several years now, and gradual introduction of React into the app didn't change the approach. We used the BEM naming methodology for our components' CSS class names and LESS mixins provided by the components to ensure theming uses the appropriate style overrides in the "partner" bundles.

 

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

return (
  <div>
    *{
      if (obj.attr) {
        yield <Stuff />;
      }
    }
  </div>
)

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!

 

I have a question about network request.

Usually I will use a isFetching state for network requesting.

  1. Initially isFetching === false, render with empty data.
  2. In componentDidMount, dispatch fetch request, set isFetching to true, render with a <Loading > component.
  3. After fetching completed, set isFetching to false, render with fetched data or error message.

Is there a good(safe) way to initially render a <Loading> component, rather than rendering with empty data. Thanks~

And the question is first asked at the stackoverflow comment.


I think using the isFetching state may not reflect the "fact", it is actually consist of the four state as the post point out:

  • Not asked
  • Loading
  • Success with data
  • Error with message

And the elm code in the post:

type RemoteData e a
    = NotAsked
    | Loading
    | Failure e
    | Success a

And we may change the state to:

state = {
  networkState: 'NotAsked', // || 'Loading' || 'Failure' || 'Success',
  data: null, // use this data only if `networkState === 'Success'
  error: null, // use this data only if `networkState === 'Failure'
}

What do you think of this approach? (This may be a second question 😅)

 

This makes sense to me. There are also other states with pagination (e.g. “nothing more to fetch”).

 

What are the best practices to organize state in Redux. I notice the we left many objects orphans inside the state and also some objects inside other objects. I know tat this is a poorly coding, but when teams are getting bigger seems to happen more. I was thinking to use something like minimongodb or other tools to validate objects. Is this a moronic idea?

 

Try to see how big apps using Redux organize their state (using Redux DevTools or by looking at storeState of connected components in React DevTools). For example Mobile Twitter.

I think in general instead of nesting you’ll want to normalize the data and keep it relatively flat. I wrote a library for this that was rewritten and is now maintained by Twitter: github.com/paularmstrong/normalizr

I don’t know what minimongodb is and I don’t understand what you mean by validating or orphan objects.

 

Minimongodb is a mongodb that is used in app that uses meteorjs. I was thinking introduce a db for the state so I can keep it normalize.

 

I learned a lot from your egghead's redux course especially the second one, are you planning to make more courses? also, where can I find similar advanced good practices and guides as mentioned in your second course?

 

I have a few ideas about future courses in mind but haven’t worked on materializing those. Maybe some time next year.

I don’t know about advanced materials. Maybe @markerikson has links?

 

I'd suggest checking out my list of suggested resources for learning Redux, and my React/Redux links list.

I also just submitted a PR that adds a "Learning Resources" page to the Redux docs, with links to some specific suggested articles on different Redux-related topics. I hope to merge it into the Redux docs and republish them within the next couple days, at which point the new page will show up in the Redux docs at redux.js.org .

 

I highly recommend Steve Kinney's course: Advanced State Management in React frontendmasters.com/courses/react-...

 

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 one question: How to make my React projects more popular? If no one see them, even the great ones can't became very popular...

And also I want to have direct chat with you, just 5-10 minutes - I'm 12 years old boy - advanced with JavaScript (SES2015/16) and PHP and learning Python and Android development (with React Native and with Kotlin).

 
  • Add website links between your Twitter and GitHub so they point at each other
  • Participate in technical discussions relevant to your area of interest in both places
  • Create good documentation for your projects and make it very clear what they do
  • Create small examples
  • Contribute to other related repositories so people start checking out your profile
  • Tweet about updates to your projects with screenshots / GIFs

Happy to chat some time, drop me an email.

 

Thanks, Dan!
I already did few of these things. Now I'm going to do the others.
All good!

 

Marketing, you need to share them and talk about them, if you're coding libraries you can share them on echojs.com, write articles about them (how to use them, what problems do they solve and how) and then publish it on your own blog or here on dev.to or another platform.

 

Hi Dan, I don't know if question I am going to ask is too simple but want to hear your views on it.

For state management in ReactJS I am using mobx but I have heard about Redux too.

So according to you which is better to use with ReactJS, Mobx or Redux?

 

Both are useful tools that try to solve state management in very different ways.

I suggest checking out these comparisons:

I also have links to additional Redux vs MobX comparisons as well.

 
 

I've mentioned this before, but this course really helped me get a deeper understanding of state management, Redux vs. Mobx in particular:
dev.to/dudeinthemirror/comment/1nb6

 

They’re just different. If one was obviously better than the other one then everybody would use it.

 
 

Hi Dan,

First, let me thank you for making this. At this point you and your ideas are kind of a basic reference in part of the industry so, being able to kind of dig into your head through this questions is just plain awesome.

Now, my question is regarding your article on Presentational and Container components, I would love to know your opinion about one thing.

Imagine that you had an app where all the state is stored in redux, from all the dynamic contents of any div to the actual state of the UI (checkboxes, inputs, form errors, menu structures, etc...), simply everything.

In that case, when all your components can be stateless because they will be grabbing everything they need from redux and dispatching everything as actions to it (and you're not building a component library that you want to be storage agnostic, of course), would you say that the whole idea of splitting components that way still makes sense or is it maybe a little bit too artificial?

Thanks in advance!

 

Hello, Dan and everybody else in this thread,

My question is about refs.

I'm using a library called react-mapbox-gl github.com/alex3165/react-mapbox-gl, which is a React wrapper for mapbox-gl-js.

My goal is to show a driving route on the map from :
1- point A to point B.
2- then a flying direction from point B to point C
3- and finally another driving direction from Point C to point D

I already managed to do that but now, I want to give the ability to the user to tap on a button to flyTo the different destination.

The mapbox-gl-js has a method called flyTo that does exactly that by passing to it the appropriate coordinates.

I'm trying to use refs to get a reference to my map by adding <Map ref={(e) => { this.map = e; }} />... and then the goal is to use that ref to call the method when the user clicks on a specific button.

I can't figure out how to use refs to get to my solution.

here are more details and my current code: github.com/alex3165/react-mapbox-g...

 
 

What is need install in react project when I wish work with bootstrap? Do you have some example of this? I am try install some like react-bootstrap, reactstrap and another what you can see in my json file
{
"name": "sajtt",
"version": "0.1.0",
"private": true,
"dependencies": {
"jquery": "3.2.1",
"react": "16.2.0",
"react-dom": "16.2.0",
"react-scripts": "1.0.17",
"react-transition-group": "2.2.1",
"reactstrap": "4.8.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"bootstrap": "3.3.7",
"bootstrap-router": "0.1.1-a",
"react-bootstrap": "0.31.5"
}
}
but I can't started use jquery. Way? Example for using image in project I must write img src={require{'imgpath/imgsrc.jpg}}. Where I make error? May be is need webpack, or babel? I wish make app for building web site singe page and multi page.
Regard
Mr.Trajanovic

 

Sorry, I don't understand what you're asking.

 

another quest is how I can use one of all data of data.json file by field Id in this file. const some=[{ "id": 0, "name": "name one"},{ "id": 1, "name": "name 1"},{ "id": 2, "name": "name 2"},{ "id": 3, "name": "name 3"}];
If I use map method react rendered all data of file. How I can get only example data where is "id": 3? I am try use


    {
    data.map((film,i)=>{
    if(i===3) {
    return (


    {film.id} ----
    {film.title}



    );

    }

    })

    }



and getwarning Expected to return a value at the end of arrow function array-callback-return.

How make that? to be glad if you have some sample

reagrad

Miodrag Trajanovic

trajanovicmiodrag@yahoo.com
 

I am find solution for this problem, but thanks to all

 

Many times (including in this thread) you've mentioned about how people should not be so "religious" about separating out container components.
I just wanted to clarify: this is only when you're managing your own state, correct? If you are using react-redux, or apollo or relay, or something like that, every time you use the libraries function for connecting your component, you are creating a container.

 
 

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...

 

Hey Dan, I know that React is just a library. But I want to ask you about the best practice to structure the project files in a react big project (+ than 100 components, react-router, redux, hoc, etc).

Thanks!

 

I have no idea! I never understood why people pay so much attention to project structures. I don’t think they’re fundamentally important but maybe I’m just missing something.

I tried to answer this here: reactjs.org/docs/faq-structure.html

 

Well, thank you so much. In my opinion it's important, it's like doing readable and maintable code, but of course it's not the most important and it's easier to change in the future than code. Just in the project that im working now, we (all the team) decided to reorganize all because the current structure is a mess. We are going to follow the recommendations of your link, thanks.

 

Hey Dan,
Thanks for this thread it already answered few of my questions!

Where I work we do separation of container and presentational components, sometimes when we do customization to components which is mostly container components I have to override methods in order for the customization to work. What I mean is that if I created component A that extends React.component, I will extend B from A and impelment the method I wish to override. I know that the react team discourage inheritance and we do use component composition but in the case i described looks suitable for a container component. What are your thoughts on this scenario?
Thanks!

 

We explicitly discourage it and will continue to. Your use case is solvable by composition just fine. Instead of overriding methods, have the “base” components take those functions as props. Then have the “concrete” components render it and pass their implementations of these methods.

 

I made an app, using react/react-router, now I need to make another one but I want to add redux to this stack, because is awesome. If in simple react, I kept some little global state in App and other state was kept in each component(by route / code splitting), how should I keep this state for entire application in redux? Should I also split state by route somehow? Thanks!

 

I think code splitting in Redux is a bit harder than it should have been. I don't really have a great solution for this, but something like stackoverflow.com/a/33044701/458193 works (it uses RR3 API but that's not the important part).

 
 

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

 

When starting and trying to make small pieces as much as possible, would you create a simple stateless component for something like an input and its label, etc.. instead of a long component managing 4 or so form fields, or quite often as long as the the component hasn't gone too crazy, splitting can be too much?

In simpler words... split all the way and create so many tiny stateless components, or this is often more writing for no benefit?

 

I’m used to working with a designer who edits my JSX to add styling to it. So I’d first write larger components and then split them to a level that I think would be most comfortable for the designer. For example if I think that the input is complex enough that the designer would consider it a separate “entity” that should be consistently styled throughout the app, I’d extract it. If it’s a one-time thing, I’d only extract it if it helps me understand the code.

 

Hi, sorry if the question is already asked. Which are the technologies or libraries you are using in your daily basis?

 

Since I’m helping build React itself I don’t use React-related libraries.

That said, we recently wrote a post about some of the newer technologies we started using inside the React repository for our internal needs: reactjs.org/blog/2017/12/15/improv...

They include Prettier, Google Closure Compiler, Rollup, Yarn (especially its Workspaces feature), Jest, Flow, and others.

 

Thanks :) was a great pleasure getting reply from you

 

Hi Dan !

I come from the angular world where we heavily use services and dependency injection. This makes the code easy to test by mocking dependencies. But when it comes to react, I cannot find a clean way to achieve the same. Is there a proper way to inject dependencies in your components ?

Thanks :)

 

I tend to either use context for this, or something like jest.mock() (that is, if you use Jest).

 

Hello Dan,

As a newcomer to Redux, one of the hardest parts of learning Redux is deciding what goes in Redux and what stays as local state.

In my case, I ended up with putting all state into Redux, since I needed both time-travelling and the ability to preload the entire application state from configuration files.

I liked the idea proposed here: medium.com/@alexmngn/how-to-use-re... which relies heavily on reducer composition. The idea of nesting components and state where it is used, and also so the state reflects the folder structure of your application. This way, your project and state is so well structured, it's actually easier just to put the state in Redux than using local state.

It seems to work pretty well, however I must say I wonder why so few people seem to recommend doing it that way. What are your opinion about this kind of structure?

If you don't have time to read the article you basically end up with a state tree such as:

{
  data: {
    users: {
      1: {
        name: 'Jorem Sipsum'
      }
    }
  },
  scenes: {    
    books: {
      loading: false,
      drawerVisible: false,
      data: {
        books: {
          1: {
            user: 1,
            title: 'JS gibberish',
            description: 'Pure Function is an e-mail message to dynamically generate Web form JavaScript engines'
          }
        }
      }
    }
  }
}

Right now I store all state for the given "scene" in redux, and the only downside I've noticed so far is that I have to clear the state per scene when navigating to another route/scene. To clear a given scenes state I was thinking about triggering an action RESET_BOOKS_STATE from the componentDidUnmount lifecycle hook of the Books view/scene/page resetting it to their default values. Is all of this some kind of anti pattern, or is this way of using redux for ALL state (no use of local state) a sane enough way of doing it? I mean, if you need that additional control as I mentioned earlier :)

 

Hi Dan,

I'm new to react world, I need to learn about React (Fiber), React Router, Redux, GraphQL, Relay or Apollo Client, may you please guide me to learn those things.

Thanks.

 

These are good guides on the order in which it’s easier to learn:

I’d suggest starting with React alone and getting comfortable with it before diving into any other technologies. You can learn React from our docs (reactjs.org/docs/hello-world.html) and tutorial (reactjs.org/tutorial/tutorial.html). There are also a few free courses available (reactjs.org/community/courses.html).

After you’re comfortable with React, check out my course on Redux. It’s also free (egghead.io/redux).

 

Thank you, I'll get back you after those things done.

 

Greetings,Dan
I would like to ask you a question. There was a dispute between me and my friend about this moment
Suppose we have a table / form, its data is stored in the redux store, respectively. And we have a button that should be turned on or off, depending on the validation of the data. It seemed strange to clog up my component or container with validation logic(in my opinion), and I put all the validation logic to the selector, which simply returned true / false for the button.
Is validation in selector a good practice? Is it a good practice to prepare data in selector in case if we I don't need recomputing?
Thank you in advance.

 

I don’t think it matters much. Either way is probably fine. If you expect to use this validation in other places or if recomputing it is expensive then yea, sure, extract it.

 

Hi Dan,

I'm new to react wanted to ask if react set states asynchronously, why it is a need for declaring on the first place State = { name: ''} when it is assigned automatically when we use this.setState({name:'Dan'})

 

So that you set the initial value without adding any lifecycle methods.

 

I've noticed that email inputs do not recognize space events that occur unless they are in between other characters. Is this a react bug, or due to browser implementation?

 

I don’t know. It’s quite possible that the browser doesn’t report them. The best way to find out is to build a DOM-only example and see if it’s an issue without React too. Or file a bug.

 

That seems to be a browser issue as spaces at beginning or end are not valid for emails. I had this issue in the past and we got to that conclusion

 

Hi Dan.

I have a React-Redux Web App where I make 5 different API calls in an action to get 5 different data sets that all need to be in the redux store before the app can function.

I'm using redux-thunk as middleware.

Problem is when one of the APIs doesn't respond for some reason, or responds too late, the app breaks.

Here's the pseudocode...
thepracticaldev.s3.amazonaws.com/i...

Can you suggest a better way of going about solving a situation like this?

Thanks!

 

You want to handle the error case as well (and maybe show a “retry” button).

This example does it: github.com/reactjs/redux/tree/mast...

 

Hello, i'm Jude.

Newbie in react and have been doing much practice with Andrei tutorials and so far it's been helpful and i'm learning it well in my own pace.

will love to get more assistance because i have seriously fallen in love with React.

Thank you Dan

 

Hi Dan,

I have been struggling to find an in-depth clarification on why this way of passing a function as a prop
" " is more optimized than passing it with using an arrow function.

 

Is there any way to react to manage the state between components? For example, a component A takes me to component B and B returns to A, but with its original state, to avoid further processing, since there is a lot of data.

 

Lift it up to their shared common ancestor. Then it will be preserved between remounting of children.

reactjs.org/docs/lifting-state-up....

 

Hi Dan!
What's the best way, in your opinion, do onScroll animation in react. It looks to me that the most performant way is to get ref to a DOM node and change styles on it directly which is not the 'React way' actually (implementing of course requestAnimationFrame and stuff). Is there a good way to implement it (talking about onscroll parallax effects) through a component state and rerender (React way)?

THNX

 

IMO that’s exactly what refs are useful for. Pretty much what I would do, yes.

 

Hi Dan,

I've been learning React Redux for last six months.But I feel like I am stuck now.I build few open source project. But I don't know if it's good or bad.

Can you please suggest me how much should I improve.Here is one of my github project using React-Router4-Redux. github.com/rahadkc/movish .

It'll help me a lot and would be honoured if you give me few tips.

Regards,
Rahad

 

Dan
I tried React and Redux once for a touchscreen, I got stuck when animating my videos, the videos would restart as I tried to animate the flexbox and css masking. I felt React had a lot of boiler plate and due to time constraints I switched to simple hxElectron and Haxe, and managed to code it all without an npm modules apart from the packaging ones. I found that by coding the html and css in Haxe the structures became simpler and the code lighter and the transpiling of haxe to js was far faster than the normal build stuff of React and I did not need to use any Webpack horrible stuff. React seemed to need extra divs for it's component approach. I am reluctant to use React but I need a job and it seems to be a standard now days, would welcome advise on reducing components and on animating divs that contain animation, webgl and canvas animations and on avoiding webpack? I have to admit that this project was my first pure js project, so the whole ecosystem seemed rather overly complex even compared to starling stuff, in the past I had made Haxe js to do pretty much anything so React seemed rather a hassle, and not really setup well for working with animation?

I have thought to explore Haxe React but unless guys like you are using it I doubt that would be useful on my CV, also I am wondering if there is much point in me looking into github.com/MVCoconut, I have looked at Angular2 but seems that React is more popular at the moment.

Is there a complex React project on github with video animation Redux etc... that I should look at to understand workflows with animation better, not touched React since the summer so something visually inspiring rather than a 'todo' demo but without too many npm dependancies?

 

The question is a bit all over the place so it’s hard to answer. This talk might be helpful regarding animation in React: youtube.com/watch?v=W5AdUcJDHo0

I don’t see why Redux would be relevant to animations and how seeing a project that does both would be helpful.

Maybe if you can narrow down your question a bit, I could answer better.

 

Thanks lovely video digging deeper codepens are a bit lacking.
I asked Sarah on twitter about React/greensocks but there was only a Babel js codepen example or I sign up to go on a workshop which I probably can't afford. Really what would be ideal for me is a simple github with basic setup instructions. Seems she's moved over to Vue as it's simpler for animation? I guess the main use of Redux was for simple logging user actions to the touchscreen to a log file. The video did not really explain too much on React and does not explain about making sure a video did not stop when playing if the mask and matrix dimensions were changed/tweened. It seemed to talk a lot about tweens (which I know how to build my own engine due to penners as2 book), but skips over much detail on react, or assume a lot of knowledge. But it was inspiring till I realised it lacked the detail for me to really know how to set something up. I don't intend to be demanding - happily help anyone setup one of the Haxe game frameworks and may well already have github stuff I can point them too so I try to share my knowlege fully. Videos are great but unless they are backed up with a github that has some build instructions then they may well be inspirational - rather than practical? I know greensocks quite well I have used it lots of cutting edge back in the day flash animations even with 3d, but the talk lacks the detail needed for me to implement and evolve something within React infact I was surprised how little react was discussed I have not looked at react since the summer. Microsoft and facebook are kind of forms people so react makes sense but beyond forms I am keen to see an animated version working without plugging in too many npm's.

 

I work with React with Redux and Saga. I need transform and validate the data from form before send it to server. Where I put the transformation and validation?

 

I don’t know, but hopefully both before you send it, and on the server (in case the request is spoofed). 🙂

As for where exactly, well, wherever you post the form. I don’t quite understand what confuses you, can you elaborate?

 

Thanks for answere, I'm big fan of your work. As you said, I need validate before send it to server, but also receive validation from the server in response. I dont know if I put this validations rules in Saga, in React component or some where ele. Today I have a custom function with custom generic validation that I use in Saga before and after post to server, and save the validation in redux store to render in components.

 

Hi Abramov,
Since react is a library to handle view, most of the dev choose a separate library(like redux and mobx) for state management.

I am curious to know, following questions
1) How Facebook handle's application state?
a) Are they using any libraries? or
b) Are they simply follow flux pattern without any libraries support?

Thanks,
Rajsek

 

FB mostly uses just Flux ReduceStore. Which is similar to Redux, but FB tends to use many stores rather than just one. For data fetching, FB mostly uses Relay (Modern where possible). A lot of components also use local state as well.

I wouldn't say any of these patterns are perfect. We're still figuring this out.

 

Hey Dan, great stuff here. I assume you are interviewing developers once in a while so I thought I'll ask a few questions about it .

I was wondering what is it that YOU are looking for in a candidate?
Do you agree with the current method of interviewing @ FB (i.e whiteboard solving CS fundamentals question)?
Do you think there's difference in the required skills between a UI developer and a UI library developer?
What is the best way in your opinion to interview a UI developer?

Thanks!

 

I’m not currently interviewing yet, as I’m actually just going through the interview training.

Do you agree with the current method of interviewing @ FB (i.e whiteboard solving CS fundamentals question)?

This is pretty inaccurate as far as I know. FB has two separate hiring pipelines. The traditional one is more CS-focused, yes. But if you apply for the “Front End Engineer” position then this assessment is not true.

Front end engineer interview doesn’t require knowledge of complex CS concepts. Instead, it checks for understanding JS/CSS fundamentals really well. It might include some algorithmic questions but they’re also related to scenarios you’re likely to encounter in front-end development (e.g. tree traversal). I think those are worthwhile questions, even if it inevitably results in some false negatives (i.e. people not getting through).

Do you think there's difference in the required skills between a UI developer and a UI library developer?

I don’t see these as distinct disciplines. I think it’s important UI developers progress so they eventually feel comfortable with extracting their knowledge in a library, or fixing existing libraries to better match their workflow.

What is the best way in your opinion to interview a UI developer?

I don’t know. It really depends on your company, how much time you’re willing to spend per candidate, whether you’d rather err on the side of false positives or false negatives, etc.

 

Hi Dan!

What are your (recent) experiences with the different options for routing within the react realm?

There’s react-native-router-flux which I’m currently using. Then there’s Wix’s react-native-navigation, AirBNB’s react-navigation and the ‘official’ react-navigation.

How do they compare?

 

I don't have experience with React Native so can't say.

 

Hi Dan!

Might be a very stupid question but are there any advantages/disadvantages in declaring a constructor vs not declaring a constructor in a class-based component?

Thanks for all your great work!

 

Hello Dan.

Dan, I need to develop an application for which React would be perfect. However, the application needs to pull data from our enterprise API instance and but to do that within React, would expose the API secret. How do I use react but protect the api secret when I fetch data?

Thanks
Eric

 

Hi Dan,

I've been programming with React for 4 months but have minimal experience with Redux. I work for an e-commerce company which is currently using PHP and a templating engine (Smarty) for the front end. We are interested in upgrading the entire front end with to use React-Redux.

I've had a hard time finding an open source code example/boiler plate for e-commerce. Are there any resources you can direct me to?

Any other pointers/gotchas I should keep in mind?

Thanks

 

I’d start by looking in the examples folder in the Redux repository itself. Other than that, I don’t really know, sorry!

 

Hello everyone, I'm new to React and I'm stuck not advancing, I want to go deeper but I do not know where. I want to handle it well, I have taken courses at Udemy and I do not feel satisfied. What courses do you recommend or guides to go in the right direction?

 

Hey Dan, just started learning React Native. I have a background of native mobile development for both Android and iOS (Swift, Java, Kotlin and a little bit of Objective C). It is really good to have a single code for generating both native apps but as far as I have been working with React Native I didn't fell that I could have the same level o customization that I would have doing it native. In Android I am used to define some XML drawables for more complex layouts and I have found a little bit difficult to add support to multilanguages in React Native. I also really miss the feature of being able to see the layout in different screen sizes and densities when I am creating or updating a layout in the IDE ( available in both XCode and Android Studio). I am still a beginner at React Native but I feel that even if I had two different code bases going native I would be more productive but at the same time I think it is maybe to soon to think that because I haven't explored deeply the power of React Native. What I would like to know is if there is a line for when would be better to go native or use some other solution like react native depending on the complexity of the application or if React Native can have the same level of customization and requirements fulfillment for any native application. Thanks =)

 

I don’t really have the experience with RN to answer this. Sorry!

 

How to style React Components the right way

I'm getting overwhelmed on the many alternatives to style my react components. It's difficult to decide which technology should I use on my new projects.

I know that we can't rely on a single solution and apply it on every project we got. Each one has it pros and cons. So I would like to hear from you how is the process for deciding which one to grab for a new project.

 
 

When organizing larger applications (no matter the language or framework) usually we start dividing it by feature. How would approach that using React and Redux?
If only React is considering, it's quite straight forward. But if there is Redux, there are two ways to approach it:

  • Group reducers, containers, components, and actions creators by feature.
  • Group components and containers by feature, but keep Redux code separately. I kind of prefer second way, because then you tend to keep Redux code (reducers, action creators) not tied to some container or feature and make it more general. But what is your take on it?
 

I don’t have an opinion on this. I find folder structures very far from being important and it’s perplexing to me how much time people spend thinking and arguing about them. 🙂

I wrote about this here: reactjs.org/docs/faq-structure.html

Redux or no Redux, it really doesn’t matter that much.

 

I've always had this question..
What is the extra costs and baggage that comes w/ rendering react on the server compared to SSR? What are the points I should consider while using SSR in a production level app?

 

How does test driven development work with React? How do I know what to test?

 

I don’t use TDD with React so I can’t say. I find it very distracting for UI code because I can’t work on UI without seeing and interacting with it.

I personally didn’t test components at all although I know many people do. If some logic is complex enough I’d extract it from component anyway, and test it separately.

Test whatever breaks in practice 🙂

 

Hi Dan,

I installed 'react app 2' as well as node-sass.
It's working fine with SCSS. But I just want to know how can I create component specific SCSS like Angular (that will never be a conflict with other components SCSS)

 

Please create a minimal example that reproduces the problem. I can’t guess it from the code alone.

 

i'm using react and react-router to develop my webapp.But i'm facing a trouble. I've a parent component contains all things about router and children components correspond url. But the children component sometime request API before parent component. Maybe children component mounts before parent. Can you explain in details components life-cycle in react

 

componentDidMount fires in children before parents.

I don't understand why it is a problem from your description.

 

Hi, Dan. Is the context API replacing redux? Is there a reason we would stick to using redux?

 

What do you think of Apollo Client for state management? I would like to hear your opinions about the future of state management.

 

I don’t know enough about Apollo Client to answer this, sorry! What do you find interesting about it?

 

Hi Dan,
I installed 'react app 2' as well as node-sass.
It's working fine with SCSS. But I just want to know how can I create component specific SCSS like Angular (that will never be a conflict with other components SCSS)

 

Hi,
what’s your opinion about react SSR and why SSR doesn’t add to CRA?

 

I'm not Dan, but my understanding is that create-react-app only focuses on the frontend and doesn't make any assumptions about backend technology stack as it wants to remain backend-agnostic, whereas implementing server-side rendering would require a particular backend technology (eg. Node.js or Ruby + ExecJS or ASP.NET + ReactJS.NET or ASP.NET + JavaScriptServices) to be chosen.