7 posts tagged

React

Dependency Injection in React With Provider Pattern

Adam Klein

The Provider pattern introduces a way to access some global object (service) in deeply nested components. If you’ve been using React for a while, you probably used it already. In fact, many popular libraries use this pattern: react-router, react-redux, mobx-react, react-intl, react-dnd, or styled-components.

A provider that wraps a component tree:

<Provider>
  <Component/>
</Provider>

An injector as higher-order function:

export default withProvider(Component);

You can also relate to this pattern as dependency injection as a mechanism of exposing a global dependency to nested components on demand, somewhat similar to Angular’s mechanism, but not as a general definition of dependency injection in software development.

Let’s say we want to create a customizable theme for our app and use it in any component we’d like:

const SendButton = () => (
  <button style={{ color: theme.primaryColor }}>Send</button>
);

Somehow we need the theme instance to be available in this component. Moreover, we want to make it reactive, meaning whenever we change the theme, we want the component to update.

Let’s start by creating a top-level component that will hold the theme, and pass it down using React context:

export class ThemeProvider extends React.Component {
  state = {
    primaryColor: '#448866'
  };

  static childContextTypes = {...};

  getChildContext() {
    return {
      getTheme: () => this.state
    };
  }

  render() {
    return <span>{ this.props.children }</span>;
  }  
};

Next, we’ll put the provider in the top-level of our app, to make the theme available everywhere:

const App = () => (
  <ThemeProvider>
    ...
  </ThemeProvider>
);

Now we need a way to access the theme from child components. We could do it directly from the context, but there are a few drawbacks to this:

  • Using context directly is not the best practice;
  • We are coupling our components to ThemeProvider;
  • We can’t use React’s lifecycle hooks to react to changes in theme.

So instead we use an injector:

function withTheme(WrappedComponent) {
  const Wrapper = (props, { getTheme }) => (
    <WrappedComponent
      getTheme={ getTheme }
      { ...props }
    />
  );

  Wrapper.contextTypes = {...};

  return Wrapper;
}

The injector is a higher-order component (HOC) that takes the theme from the context and passes it down as props. Now to use the theme inside a component, you wrap it with the withTheme HOC:

const Component = (props) => (
  <div style={{ color: props.getTheme().primaryColor }}>
    This is the primary color
  </div>
);

export default withTheme(Component);

Reusing a service

Let’s now say we want to have two different themes side by side on our page. Since we are using context, we just need to put two ThemeProvider’s and each one of them will supply a different theme instance for its component subtree:

<div>
  Theme 1:
  <ThemeProvider>
     ... // components using theme 1
  </ThemeProvider>

  Theme 2:
  <ThemeProvider>
    ... // components using theme 2
  </ThemeProvider>
</div>

See full source code and demo on StackBlitz

When to use the pattern

Usually you can use generic store mechanisms like React and MobX to access global resources, but in some cases Redux and MobX are not good enough:

  • You are creating a generic component that should serve any architecture (for example if you create styled-components and want to supply a theme);
  • You need the services to be reusable on the page, and be able to declare a service per component tree;
  • You need to save large amounts of data that you don’t want on the store.

Other (bad) approaches

You could pass the theme down the component tree as a prop. In this case all the component’s ancestors have to be aware of the theme and pass it down which creates coupling, and is not a very productive way of writing code.

You could also export a theme object and import it wherever you need. In this case it won’t be reactive out of the box, meaning if we change the theme it won’t be reflected in the components that use it. Also, if we want to support showing two themes on the same page we can’t do that with a global singleton.

ReactNext 2017 Highlights

Ilya Gelman

Last September we held ReactNext 2017, our annual React conference in Tel Aviv. This year we had an honor to welcome over 700 attendees from 15 countries for a full day focused on React and React Native with 20 speakers in two tracks.

We have published the videos of the presentations on the conference YouTube channel (the link is at the end of the post) and wanted to highlight some of the talks.

The biggest piece of news in React ecosystem this year is the release of React 16 with a completely rewritten reconciliation engine called Fiber (and a new license). Ari Lerner covered all the awesome features that came with the new release (and virtually no breaking changes).

Ari Lerner goes through new features in React 16

One of the most interesting presentations was probably Michel Weststrate’s talk about mobx-state-tree, his opinionated state container for applications. Many people will now consider it as a serious alternative to Redux.

Michel Weststrate released mobx-state-tree

Speaking about state management, Boris Dinkevich gave an advanced talk on some of the most powerful—yet underestimated—features of Redux, middleware. Must watch if you use Redux in your application.

Boris Dinkevich teaches Redux middleware

Many companies that develop web and mobile applications using React and React Native want to reuse as much code between platforms as possible. Peggy Rayzis shared her practical experience on how to reuse more code with universal components.

Peggy Rayzis talks about universal components

Finally we’d like to highlight a presentation of a great tool that will save countless hours to companies that seriously use React Native. Rotem Mizrachi-Meidan talked about Detox, end-to-end testing and automation library for mobile apps developed by Wix.

Rotem Mizrachi-Meidan introduces Detox

We had a great time organizing and attending the conference and hope all the guests, speakers, and sponsors enjoyed it as much as we did. You can find the rest of the videos on the conference YouTube channel.

Follow ReactNext on Facebook and Twitter for more updates, photos from the event, and future announcements.

Conferences   React   ReactNext   Video

Where to Start Learning React

Ilya Gelman

React is a mature library with a vast ecosystem. Therefore there is a plethora of resources available from short blog posts to paid online courses. It is easy to get lost there, especially if you can’t assess the quality. However, you don’t need much to get a good basic knowledge.

Before you start learning React though, it is essential to have a good JavaScript knowledge and understanding. React doesn’t come with custom templating language and has very few APIs. Most of the time you are using pure JavaScript.

When learning React, most questions people have are actually related to JavaScript. Questions like “why can’t I use `this` in class method” or “why can’t I use if statement in JSX” are more common than “what does this specific lifecycle event does”.

Another tip: do not rush and try to learn React together with Redux (or MobX). I’ve seen a lot of tutorials that teach both from the get go, and as much as I love Redux (even wrote a book about it), I think it is very important to understand React first before working with either Redux or MobX. Developers that tend to do so, often fail to realize that the magic behind the connect() function from react-redux is just this.setState().

There are a lot of lists of the top resources for learning React, but in fact, you don’t need much. See for yourself:

Read the Documentation

As obvious as it sounds, surprisingly many people still don’t think of the official docs as the primary resource for learning React. They may not have been the best source in the early days, but they have been rewritten and are actually pretty good now.

Free Video

There are many great courses on Egghead.io, but I would recommend starting with the one by Joe Maddalone’s course Start Learning React followed by Nik Graf’s one on new features of React 16.

Free Book

If you prefer to learn from a good book, take a look at Robin Wieruch’s The Road to Learn React. Surprisingly, many parts of this book are about JavaScript, and he explains a lot of concepts in an easy way.

As you can see, you don’t need a lot of resources to grasp the basics of React. Obviously, it is not enough to become a good developer, but having a good base would allow you to learn other things much faster and make fewer mistakes.

React   Training

Celebrating ReactNYC Halfiversary

Ilya Gelman

Sharing knowledge and supporting developers community was always one of the more important things for us at 500Tech.

Last week we celebrated six months for ReactNYC, our meetup for React and React Native developers in New York City. Hard to believe, but in such a short period of time we’ve got over 2300 members, hosted 15 events at 11 companies with almost 40 speakers, got over 400 followers on Twitter and four sponsors.

Organizing such a vibrant community isn’t easy, and luckily a lot of co-organizers are building the community with us. We owe a huge thanks to Kirill Cherkashin, Roman Ilyushin, Liron Burrack, Tessa Park, Ringo Kam, and many others.

At the kickoff meetup, when we saw a line around the block, it was obvious that it would be a huge success. The enthusiasm for React in New York is just amazing.

It is empowering to see so many people at every event. Developers come to learn new things, share their ideas, network with other developers and find a new job. Thanks everyone for coming and being a part of such a great community!

Apart from great talks, presentations, and workshops, we believe that meetups should also be fun. React Quizes and games like React Lifecycle Bingo, React Feud, React Taboo, and Guess the 3rd-party make the atmosphere more chill and inviting for everyone.

Ken Wheeler explains how to build Westworld with React
Kent C. Dodds makes the audience do squats
Ryan Florence rocks

The past half year was great and we have big plans for the future.

If you are visiting New York, be sure to check out the meetups we’re involved with: ReactNYC, AngularNYC, and VueNYC. We also run the Angular Israel and React Israel meetups in Tel-Aviv.

See more videos from the meetup at ReactNYC YouTube channel or from our other events at our company YouTube Channel
Community   Meetups   React
Earlier Ctrl + ↓