Inferno

An extremely fast, React-like JavaScript library for building modern user i...

README

Inferno

Build Status Coverage Status MIT NPM npm downloads Discord gzip size Backers on Open Collective Sponsors on Open Collective

Inferno is an insanely fast, React-like library for building high-performance user interfaces on both the client and server.

Description


The main objective of the InfernoJS project is to provide the fastest possible runtime performance for web applications. Inferno excels at rendering real time data views or large DOM trees.

The performance is achieved through multiple optimizations, for example:

- Inferno's own JSX plugin creates monomorphiccreateVNode calls, instead of createElement
- Inferno's diff process uses bitwise flags to memoize the shape of objects
- Child nodes are normalized only when needed
- Special JSX flags can be used during compile time to optimize runtime performance at application level
- Many micro optimizations

Features


- Component driven + one-way data flow architecture
- React-like API, concepts and component lifecycle events
- Partial synthetic event system, normalizing events for better cross browser support
- Inferno's [linkEvent](https://github.com/infernojs/inferno/blob/master/README.md#linkevent-package-inferno) feature removes the need to use arrow functions or binding event callbacks
- Isomorphic rendering on both client and server with inferno-server
- Unlike React and Preact, Inferno has lifecycle events on functional components
- Unlike Preact and other React-like libraries, Inferno has controlled components for input/select/textarea elements
- Components can be rendered outside their current html hierarchy using createPortal - API
- Support for older browsers without any polyfills
- defaultHooks for Functional components, this way re-defining lifecycle events per usage can be avoided
- Inferno supports setting styles using string `
` or using object literal syntax `
`. For camelCase syntax support see [`inferno-compat`](https://github.com/infernojs/inferno/tree/master/packages/inferno-compat).
- Fragments (v6)
- createRef and forwardRef APIs (v6)
- componentDidAppear, componentWillDisappear and componentWillMove (v8) - class and function component callbacks to ease animation work, see inferno-animation package

Browser support

Since version 4 we have started running our test suite without any polyfills.
Inferno is now part of Saucelabs open source program and we use their service for executing the tests.

InfernoJS is actively tested with browsers listed below, however it may run well on older browsers as well.
Browser Test Status

Migration guides



Benchmarks




Code Example


Let's start with some code. As you can see, Inferno intentionally keeps the same design ideas as React regarding components: one-way data flow and separation of concerns.

In these examples, JSX is used via the Inferno JSX Babel Plugin to provide a simple way to express Inferno virtual DOM. You do not need to use JSX, it's completelyoptional, you can use hyperscript or createElement (like React does).
Keep in mind that compile time optimizations are available only for JSX.

  1. ``` js
  2. import { render } from 'inferno';

  3. const message = "Hello world";

  4. render(
  5.   <MyComponent message={ message } />,
  6.   document.getElementById("app")
  7. );
  8. ```
Furthermore, Inferno also uses ES6 components like React:

  1. ``` js
  2. import { render, Component } from 'inferno';

  3. class MyComponent extends Component {
  4.   constructor(props) {
  5.     super(props);
  6.     this.state = {
  7.       counter: 0
  8.     };
  9.   }
  10.   render() {
  11.     return (
  12.       <div>
  13.         <h1>Header!</h1>
  14.         <span>Counter is at: { this.state.counter }</span>
  15.       </div>
  16.     );
  17.   }
  18. }

  19. render(
  20.   <MyComponent />,
  21.   document.getElementById("app")
  22. );
  23. ```

Because performance is an important aspect of this library, we want to show you how to optimize your application even further.
In the example below we optimize diffing process by using JSX $HasVNodeChildren and $HasTextChildren to predefine children shape compile time.
In the MyComponent render method there is a div that contains JSX expression node as its content. Due to dynamic nature of Javascript
that variable node could be anything and Inferno needs to go through the normalization process to make sure there are no nested arrays or other invalid data.
Inferno offers a feature called ChildFlags for application developers to pre-define the shape of vNode's child node. In this example case
it is using $HasVNodeChildren to tell the JSX compiler, that this vNode contains only single element or component vNode.
Now inferno will not go into the normalization process runtime, but trusts the developer decision about the shape of the object and correctness of data.
If this contract is not kept and node variable contains invalid value for the pre-defined shape (fe. null), then application would crash runtime.
There is also span-element in the same render method, which content is set dynamically through _getText() method. There $HasTextChildren child-flag
fits nicely, because the content of that given "span" is never anything else than text.
All the available child flags are documented here.

  1. ``` js
  2. import { createTextVNode, render, Component } from 'inferno';

  3. class MyComponent extends Component {
  4.   constructor(props) {
  5.     super(props);
  6.     this.state = {
  7.       counter: 0
  8.     };
  9.   }

  10.   _getText() {
  11.      return 'Hello!';
  12.   }
  13.   
  14.   render() {
  15.     const node = this.state.counter > 0 ? <div>0</div> : {this._getText()}span>;
  16.       
  17.     return (
  18.       <div>
  19.         <h1>Header!</h1>
  20.         <div $HasVNodeChildren>{node}</div>
  21.       </div>
  22.     );
  23.   }
  24. }

  25. render(
  26.   <MyComponent />,
  27.   document.getElementById("app")
  28. );
  29. ```

Tear down


To tear down inferno application you need to render null on root element.
Rendering null will trigger unmount lifecycle hooks for whole vDOM tree and remove global event listeners.
It is important to unmount unused vNode trees to free browser memory.

  1. ``` js
  2. import { createTextVNode, render, Component } from 'inferno';

  3. const rootElement = document.getElementById("app");

  4. // Start the application
  5. render(
  6.   <ExampleComponent/>,
  7.   rootElement
  8. );

  9. // Tear down
  10. render(
  11.   null,
  12.   rootElement
  13. );

  14. ```


More Examples


If you have built something using Inferno you can add them here:

- [Simple Clock (@JSFiddle)](https://jsfiddle.net/xo5jfe64/)
- [Simple JS Counter (@github/scorsi)](https://github.com/scorsi/simple-counter-inferno-cerebral-fusebox): SSR Inferno (view) + Cerebral (state manager) + FuseBox (build system/bundler)
- [Online interface to TMDb movie database (@codesandbox.io)](https://codesandbox.io/s/9zjo5yx8po): Inferno + Inferno hyperscript (view) + Superagent (network requests) + Web component (custom elements v1) + state-transducer
(state machine library)
- [Lemmy - a self-hostable reddit alternative (front end in Inferno)](https://github.com/dessalines/lemmy)

Getting Started


The easiest way to get started with Inferno is by using Create Inferno App.

Alternatively, you can try any of the following:
the Inferno Boilerplate for a very simple setup.
for a more advanced example demonstrating how Inferno might be used, we recommend trying out Inferno Starter Project by nightwolfz.
for using Inferno to build a mobile app, try Inferno Mobile Starter Project by Rudy-Zidan.
for TypeScript support and bundling, check out ts-plugin-inferno, or inferno-typescript-example.
for an example of how to use Inferno in codesandbox: https://codesandbox.io/s/znmyj24w4p

Core package:

  1. ```sh
  2. npm install --save inferno
  3. ```

Addons:

  1. ```sh
  2. # server-side rendering
  3. npm install --save inferno-server
  4. # routing
  5. npm install --save inferno-router
  6. ```

Pre-bundled files for browser consumption can be found on our cdnjs:

Or on jsDelivr:

  1. ```
  2. https://cdn.jsdelivr.net/npm/inferno@latest/dist/inferno.min.js
  3. ```

Or on unpkg.com:

  1. ```
  2. https://unpkg.com/inferno@latest/dist/inferno.min.js
  3. ```

Creating Virtual DOM


JSX:

  1. ```sh
  2. npm install --save-dev babel-plugin-inferno
  3. ```

Hyperscript:

  1. ```sh
  2. npm install --save inferno-hyperscript
  3. ```

createElement:

  1. ```sh
  2. npm install --save inferno-create-element
  3. ```

Compatibility with existing React apps

  1. ```sh
  2. npm install --save-dev inferno-compat
  3. ```

Note: Make sure you read more about [inferno-compat](https://github.com/infernojs/inferno/tree/master/packages/inferno-compat) before using it.

Third-party state libraries


Inferno now has bindings available for some of the major state management libraries out there:

- Redux via [inferno-redux](https://github.com/infernojs/inferno/tree/dev/packages/inferno-redux)
- MobX via [inferno-mobx](https://github.com/infernojs/inferno/tree/dev/packages/inferno-mobx)
- Cerebral via [@cerebral/inferno](https://github.com/cerebral/cerebral/tree/master/packages/node_modules/@cerebral/inferno)

JSX


Inferno has its own JSX Babel plugin.

Differences from React


- Inferno doesn't have a fully synthetic event system like React does. Inferno has a partially synthetic event system, instead opting to only delegate certain events (such as onClick).
- Inferno doesn't support React Native. Inferno was only designed for the browser/server with the DOM in mind.
- Inferno doesn't support legacy string refs, use createRef or callback ref API
- Inferno provides lifecycle events on functional components. This is a major win for people who prefer lightweight components rather than ES2015 classes.

Differences from Preact


- Inferno has a partial synthetic event system, resulting in better performance via delegation of certain events.
- Inferno is much faster than Preact in rendering, updating and removing elements from the DOM. Inferno diffs against virtual DOM, rather than the real DOM (except when loading from server-side rendered content), which means it can make drastic improvements. Unfortunately, diffing against the real DOM has a 30-40% overhead cost in operations.
- Inferno fully supports controlled components for input/select/textarea elements. This prevents lots of edgecases where the virtual DOM is not the source of truth (it should always be). Preact pushes the source of truth to the DOM itself.
- Inferno provides lifecycle events on functional components. This is a major win for people who prefer lightweight components rather than ES2015 classes.

Event System


Like React, Inferno also uses a light-weight synthetic event system in certain places (although both event systems differ massively). Inferno's event system provides highly efficient delegation and an event helper called [linkEvent](https://github.com/infernojs/inferno/blob/master/README.md#linkevent-package-inferno).

One major difference between Inferno and React is that Inferno does not rename events or change how they work by default. Inferno only specifies that events should be camel cased, rather than lower case. Lower case events will bypass
Inferno's event system in favour of using the native event system supplied by the browser. For example, when detecting changes on an `` element, in React you'd use `onChange`, with Inferno you'd use `onInput` instead (the
native DOM event is oninput).

Available synthetic events are:
- onClick
- onDblClick
- onFocusIn
- onFocusOut
- onKeyDown
- onKeyPress
- onKeyUp
- onMouseDown
- onMouseMove
- onMouseUp
- onTouchEnd
- onTouchMove
- onTouchStart

linkEvent (package: inferno)


linkEvent() is a helper function that allows attachment of props/state/context or other data to events without needing to bind() them or use arrow functions/closures. This is extremely useful when dealing with events in functional components. Below is an example:

  1. ``` js
  2. import { linkEvent } from 'inferno';

  3. function handleClick(props, event) {
  4.   props.validateValue(event.target.value);
  5. }

  6. function MyComponent(props) {
  7.   return <div><input type="text" onClick={ linkEvent(props, handleClick) } /><div>;
  8. }
  9. ```

This is an example of using it with ES2015 classes:


  1. ``` js
  2. import { linkEvent, Component } from 'inferno';

  3. function handleClick(instance, event) {
  4.   instance.setState({ data: event.target.value });
  5. }

  6. class MyComponent extends Component {
  7.   render () {
  8.     return <div><input type="text" onClick={ linkEvent(this, handleClick) } /><div>;
  9.   }
  10. }
  11. ```

linkEvent() offers better performance than binding an event in a class constructor and using arrow functions, so use it where possible.


Controlled Components


In HTML, form elements such as ``, `