Friday, September 4, 2020

React.Component

 

Overview

React lets you define components as classes or functions. Components defined as classes currently provide more features which are described in detail on this page. To define a React component class, you need to extend React.Component:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

The only method you must define in a React.Component subclass is called render(). All the other methods described on this page are optional.

We strongly recommend against creating your own base component classes. In React components, code reuse is primarily achieved through composition rather than inheritance.

Note:

React doesn’t force you to use the ES6 class syntax. If you prefer to avoid it, you may use the create-react-class module or a similar custom abstraction instead. Take a look at Using React without ES6 to learn more.

The Component Lifecycle

Each component has several “lifecycle methods” that you can override to run code at particular times in the process. You can use this lifecycle diagram as a cheat sheet. In the list below, commonly used lifecycle methods are marked as bold. The rest of them exist for relatively rare use cases.

Mounting

These methods are called in the following order when an instance of a component is being created and inserted into the DOM:

Note:

These methods are considered legacy and you should avoid them in new code:

Updating

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

Note:

These methods are considered legacy and you should avoid them in new code:

Unmounting

This method is called when a component is being removed from the DOM:

Error Handling

These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.

Other APIs

Each component also provides some other APIs:

Class Properties

Instance Properties


Reference

Commonly Used Lifecycle Methods

The methods in this section cover the vast majority of use cases you’ll encounter creating React components. For a visual reference, check out this lifecycle diagram.

render()

render()

The render() method is the only required method in a class component.

When called, it should examine this.props and this.state and return one of the following types:

  • React elements. Typically created via JSX. For example, <div /> and <MyComponent /> are React elements that instruct React to render a DOM node, or another user-defined component, respectively.
  • Arrays and fragments. Let you return multiple elements from render. See the documentation on fragments for more details.
  • Portals. Let you render children into a different DOM subtree. See the documentation on portals for more details.
  • String and numbers. These are rendered as text nodes in the DOM.
  • Booleans or null. Render nothing. (Mostly exists to support return test && <Child /> pattern, where test is boolean.)

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.

If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about.

Note

render() will not be invoked if shouldComponentUpdate() returns false.


constructor()

constructor(props)

If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Typically, in React constructors are only used for two purposes:

You should not call setState() in the constructor(). Instead, if your component needs to use local state, assign the initial state to this.state directly in the constructor:

constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}

Constructor is the only place where you should assign this.state directly. In all other methods, you need to use this.setState() instead.

Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead.

Note

Avoid copying props into state! This is a common mistake:

constructor(props) {
 super(props);
 // Don't do this!
 this.state = { color: props.color };
}

The problem is that it’s both unnecessary (you can use this.props.color directly instead), and creates bugs (updates to the color prop won’t be reflected in the state).

Only use this pattern if you intentionally want to ignore prop updates. In that case, it makes sense to rename the prop to be called initialColor or defaultColor. You can then force a component to “reset” its internal state by changing its key when necessary.

Read our blog post on avoiding derived state to learn about what to do if you think you need some state to depend on the props.


componentDidMount()

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the constructor() instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.


componentDidUpdate()

componentDidUpdate(prevProps, prevState, snapshot)

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If you’re trying to “mirror” some state to a prop coming from above, consider using the prop directly instead. Read more about why copying props into state causes bugs.

If your component implements the getSnapshotBeforeUpdate() lifecycle (which is rare), the value it returns will be passed as a third “snapshot” parameter to componentDidUpdate(). Otherwise this parameter will be undefined.

Note

componentDidUpdate() will not be invoked if shouldComponentUpdate() returns false.


componentWillUnmount()

componentWillUnmount()

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

You should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.


Error boundaries

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch(). Updating state from these lifecycles lets you capture an unhandled JavaScript error in the below tree and display a fallback UI.

Only use error boundaries for recovering from unexpected exceptions; don’t try to use them for control flow.

For more details, see Error Handling in React 16.

Note

Error boundaries only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself.

static getDerivedStateFromError()

static getDerivedStateFromError(error)

This lifecycle is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {    // Update state so the next render will show the fallback UI.    return { hasError: true };  }
  render() {
    if (this.state.hasError) {      // You can render any custom fallback UI      return <h1>Something went wrong.</h1>;    }
    return this.props.children; 
  }
}

Note

getDerivedStateFromError() is called during the “render” phase, so side-effects are not permitted. For those use cases, use componentDidCatch() instead.


componentDidCatch()

componentDidCatch(error, info)

This lifecycle is invoked after an error has been thrown by a descendant component. It receives two parameters:

  1. error - The error that was thrown.
  2. info - An object with a componentStack key containing information about which component threw the error.

componentDidCatch() is called during the “commit” phase, so side-effects are permitted. It should be used for things like logging errors:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {    // Example "componentStack":    //   in ComponentThatThrows (created by App)    //   in ErrorBoundary (created by App)    //   in div (created by App)    //   in App    logComponentStackToMyService(info.componentStack);  }
  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

Note

In the event of an error, you can render a fallback UI with componentDidCatch() by calling setState, but this will be deprecated in a future release. Use static getDerivedStateFromError() to handle fallback rendering instead.


Other APIs

Unlike the lifecycle methods above (which React calls for you), the methods below are the methods you can call from your components.

There are just two of them: setState() and forceUpdate().

setState()

setState(updater, [callback])

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

setState() will always lead to a re-render unless shouldComponentUpdate() returns false. If mutable objects are being used and conditional rendering logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

The first argument is an updater function with the signature:

(state, props) => stateChange

state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props. For instance, suppose we wanted to increment a value in state by props.step:

this.setState((state, props) => {
  return {counter: state.counter + props.step};
});

Both state and props received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with state.

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

You may optionally pass an object as the first argument to setState() instead of a function:

setState(stateChange[, callback])

This performs a shallow merge of stateChange into the new state, e.g., to adjust a shopping cart item quantity:

this.setState({quantity: 2})

This form of setState() is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:

Object.assign(
  previousState,
  {quantity: state.quantity + 1},
  {quantity: state.quantity + 1},
  ...
)

Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:

this.setState((state) => {
  return {quantity: state.quantity + 1};
});

For more detail, see:


forceUpdate()

component.forceUpdate(callback)

By default, when your component’s state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().

Calling forceUpdate() will cause render() to be called on the component, skipping shouldComponentUpdate(). This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child. React will still only update the DOM if the markup changes.

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().


Class Properties

defaultProps

defaultProps can be defined as a property on the component class itself, to set the default props for the class. This is used for undefined props, but not for null props. For example:

class CustomButton extends React.Component {
  // ...
}

CustomButton.defaultProps = {
  color: 'blue'
};

If props.color is not provided, it will be set by default to 'blue':

  render() {
    return <CustomButton /> ; // props.color will be set to blue
  }

If props.color is set to null, it will remain null:

  render() {
    return <CustomButton color={null} /> ; // props.color will remain null
  }

displayName

The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component, see Wrap the Display Name for Easy Debugging for details.


Instance Properties

props

this.props contains the props that were defined by the caller of this component. See Components and Props for an introduction to props.

In particular, this.props.children is a special prop, typically defined by the child tags in the JSX expression rather than in the tag itself.

state

The state contains data specific to this component that may change over time. The state is user-defined, and it should be a plain JavaScript object.

If some value isn’t used for rendering or data flow (for example, a timer ID), you don’t have to put it in the state. Such values can be defined as fields on the component instance.

See State and Lifecycle for more information about the state.

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

Tuesday, September 1, 2020

Top 10 React Component Libraries for 2020

 It’s 2020 and React is still one of the most loved frontend libraries around.

The React community is also growing rapidly as more React packages are created to simplify various aspects of development with React.

In this post, we’ll take a look at the fastest growing React libraries over the past year as well as some of of their use cases.

N.B.: This post assumes you know or use React. If you want to learn more about React, check out the docs here.

Ant Design

Ant Design is a set of enterprise-class UI designed for web applications.

It provides over 50 customizable components that can be used to craft beautiful applications.

Ant Design recently beat material UI to become the most popular React UI library on GitHub with over 56k stars.

Every aspect of Ant Design is completely thought-out down to the smallest detail. It’s built based on a design system created by the makers.

It is specially created for internal desktop applications and is based on several principles and unitary specifications. It makes design and prototype more simple and accessible for all of a project’s members.

If you’d like to create applications that provide a native feel for your users, definitely check it out.

There’s also a mobile version of Ant Design. You can learn more about it here.

Material UI

MaterialUI is a set of components built based on the material design guidelines of Google.

Material UI consists of many accessible and configurable UI widgets.

The components are self-supporting and only inject the styles they need to display, which could lead to performance enhancements in your application.

MaterialUI has an active set of maintainers and a strong community behind it. It currently has over 54k stars on GitHub, making it one of the most popular component libraries out there.

It provides a simple, light, and user-friendly layout and design to make building beautiful applications a breeze.

Using it is borrowing from the Google design team’s wealth of knowledge of how consistent and easy-to-use interfaces should look.

If you’re looking to build a beautiful, consistent, and light interface quickly without sacrificing accessibility and performance, material design will help you achieve that.

You can get started here.

React Bootstrap

React Bootstrap is a UI kit based on the bootstrap library.

It simply replaces the JavaScript in the regular Bootstrap components with React code.

Using React bootstrap is often intuitive to use because of the number of available bootstrap themes.

It is arguably the fastest way to get started building interfaces using React and Bootstrap.

It has gained popularity over the years and now has over 17k stars on GitHub.

It also gathers over 500k downloads on npm weekly.

If you want to build React apps quickly, React Bootstrap can be very useful.

It’s world’s most popular front-end component library, and it has a lot of starter kit, resources, and themes readily available for use.

Blueprint UI

Blueprint is a React-based UI toolkit for the web.

It is optimized for building complex, data-dense web interfaces for desktop applications that run in modern browsers and IE11.

It is not a mobile-first UI toolkit.

From the component library, you can pick up bits of code for generating and displaying icons, interacting with dates and times, picking timezones, and more.

With over 15k stars on GitHub and a weekly download of over 100k on npm, it is one of the fastest-growing UI libraries in the past year.

If you’re building something that needs to deal with a lot of data and a lot of flexibility, then consider taking a look at Blueprint.

To get an overview of how it works and the components it offers, you can check it out on CodeSandbox here.

Semantic UI React

Semantic UI React is the official React integration for Semantic UI.

Semantic UI is a jQuery-based library that adds extra functionality to your pipeline.

With Semantic UI React, all the extra functionality has been re-written to React code.

You’ll use JSX code to directly define the components and bind it with its React component code.

It comes with a huge list of prebuilt components designed specifically to make sense of and produce Semantic-friendly code.

It has over 10.6k stars on GitHub and is being downloaded over 100k times each week from npm.

If you’re looking to build apps with React and want to ensure 100 percent Semantic-friendly code, you should definitely check it out.

Be advised that the creator of Semantic UI React has noted that the project has moved into more of a maintenance mode since March after he began working on the team developing Microsoft’s Fluent UI library — more on that below.

Rebass

Rebass is a tiny UI components library capable of creating a very powerful set of theme-able UI elements based on the Styled System library.

Rebass contains only eight foundational components in a super-small file, all built specifically for responsive web design.

The components use styled-system and serve as a great starting point for extending into custom UI components for your app using its inbuilt ThemeProvider.

If you don’t want to rely completely on component libraries and intend to extend an already existing one during development, you should definitely check out Rebass.

It’s rapidly gaining popularity. The project currently has over 6k stars on GitHub and gathers around 130k downloads per month from npm.

Fluent UI

Formerly known as Fabric React, Fluent UI is another exciting UI library created by the Microsoft dev team.

Fluent UI provides components with behaviors and graphics similar to office products.

The UI library offers compatibility with Desktop, Android, and iOS devices and is used by sites such as Office 365, OneNote, Azure DevOps, and other Microsoft products.

It is packed with a lot of prebuilt components that can be used to develop most parts of any application, and its design follows Microsoft’s Office Design Language.

If you’re creating a web app with office-like UI, consider taking a look at this.

It’s rapidly gaining popularity: the project currently has over 8.5k stars on GitHub and more than 8k downloads per week from npm.

Evergreen UI

Evergreen is a React UI Framework for building ambitious products on the web. It was created by the developers at Segment.

One of the best things about Evergreen is their detailed explanation of their design decisions.

It provides a set of components for building essential features of a web application.

Evergreen’s design is light, simple, and intuitive. You can use it to get started building elegant user interfaces pretty quickly.

It’s also rapidly gaining popularity, and currently has over 9k stars on GitHub with over 100 contributors.

Chakra UI

Chakra UI is a simple, modular, and accessible component library that gives you all the building blocks you need to build React applications.

Chakra UI contains a set of layout components like Box and Stack that make it easy to style your components by passing props.

One thing I personally love about it is that most of the components are dark mode compatible.

It can get you started with building simple, composable components that cater to real-world UI design problems.

In just a few months, it has gained over 4k stars on GitHub and earned a lot of positive comments from top React developers.

You can get started by checking out the docs here.

Grommet

Grommet is a React-based framework that provides accessibility, modularity, responsiveness, and themes in a tidy package.

Grommet helps build responsive and accessible mobile-first projects for the web with an easy to use component library.

One of the best things about grommet is that you can easily integrate it with existing projects or when starting out with new ones.

Big names like Netflix and Boeing are among its users.

For small screen phones or for wider screen displays, Grommet will help you quickly design layouts.

It provides support for W3c’s WCAG 2.1 spec and provides accessibility via keyboard or screen reader.

Grommet is also growing with about 5k stars on GitHub.

To find out more click here.

Conclusion

In this tutorial, we looked at the 10 most popular and fastest-growing React component libraries available today. We also looked at the type of applications where they fit best.

Before diving into react projects, you should take time to review these frameworks as they can save you a ton of time during development.

Happy coding!