react, vue, svelte, preact, and inferno are all libraries designed to build interactive user interfaces, but they employ fundamentally different runtime models and architectural patterns. react popularized the virtual DOM and unidirectional data flow, relying on a reconciliation algorithm to update the browser DOM efficiently. vue offers a similar virtual DOM approach but includes a more comprehensive built-in ecosystem for state management and routing, with a reactivity system based on proxies. svelte shifts the work to compile time, generating imperative code that surgically updates the DOM without a virtual DOM overhead. preact and inferno are lightweight alternatives to React, optimizing the virtual DOM diffing process for speed and size while maintaining API compatibility or introducing performance-specific tweaks.
When selecting a UI library for a professional application, the decision often comes down to how the library manages state changes and updates the browser DOM. react, vue, svelte, preact, and inferno all solve the same problem but use different strategies to get there. Understanding these underlying mechanisms is crucial for making the right architectural choice.
The biggest divide in this group is between libraries that use a Virtual DOM and those that use a Compiler.
react, vue, and preact rely on a Virtual DOM. They keep a lightweight copy of the UI in memory. When state changes, they create a new virtual tree, compare it to the previous one (diffing), and calculate the minimal set of changes needed for the real browser DOM.
// react/preact/vue style: Declarative Virtual DOM
import { useState } from 'react'; // or 'preact/hooks'
function Counter() {
const [count, setCount] = useState(0);
// Re-renders the whole virtual tree on change
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
svelte takes a different approach. It runs a compiler at build time that analyzes your code and generates highly optimized, imperative JavaScript. There is no Virtual DOM at runtime. The generated code knows exactly which DOM node to update.
// svelte style: Compiled Imperative Updates
<script>
let count = 0;
// The compiler generates code to update only the text node
</script>
<button on:click={() => count++}>
{count}
</button>
inferno also uses a Virtual DOM but optimizes the diffing process aggressively using flags to skip comparisons for static parts of the tree, aiming for raw speed in specific scenarios.
// inferno style: Optimized Virtual DOM
import { Component } from 'inferno';
class Counter extends Component {
state = { count: 0 };
render() {
// Uses flags to optimize diffing of static vs dynamic children
return <button onClick={() => this.setState({ count: this.state.count + 1 })}>
{this.state.count}
</button>;
}
}
How the library detects changes determines how you write your code.
react and preact require you to explicitly tell the library when data has changed by calling a setter function (like setState or useState). If you mutate an object directly, the UI will not update.
// react/preact: Explicit state updates
function User({ user }) {
const [name, setName] = useState(user.name);
const handleChange = (e) => {
// Must call setter to trigger re-render
setName(e.target.value);
};
return <input value={name} onChange={handleChange} />;
}
vue uses a proxy-based reactivity system. It can detect when properties on an object are changed automatically, though it still encourages using specific APIs for clarity.
// vue: Proxy-based Reactivity
import { reactive } from 'vue';
export default {
setup() {
const state = reactive({ name: 'Alice' });
const handleChange = (e) => {
// Direct mutation triggers update because 'state' is a proxy
state.name = e.target.value;
};
return { state, handleChange };
}
};
svelte makes reactivity feel like standard JavaScript assignment. The compiler transforms simple assignments into update calls behind the scenes.
// svelte: Compiler-transformed Assignment
<script>
let name = 'Alice';
function handleChange(e) {
// Simple assignment triggers UI update
name = e.target.value;
}
</script>
<input bind:value={name} />
inferno follows the React pattern of explicit state management but allows for some direct mutation optimizations if you manually manage lifecycle methods, though this is advanced usage.
// inferno: Explicit State
import { render } from 'inferno';
const state = { count: 0 };
function update() {
state.count++;
// Must manually trigger render or use setState in components
render(<App />, document.body);
}
The way you define a component varies significantly, impacting code organization and readability.
react and preact have standardized on Function Components with Hooks. This is now the dominant pattern for both.
// react/preact: Function Component with Hooks
function Button({ label }) {
return <button>{label}</button>;
}
vue supports both the Options API (good for beginners) and the Composition API (better for complex logic reuse). The Composition API looks very similar to React Hooks.
// vue: Composition API
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
return { count };
}
};
svelte uses a single-file component structure where logic, markup, and styles live together in a .svelte file. There is no need to import a render function.
// svelte: Single File Component
<script>
export let label;
</script>
<button>{label}</button>
<style>
button { color: blue; }
</style>
inferno supports both Functional Components and Class Components. It is known for maintaining strong support for Class components, which some legacy React codebases rely on.
// inferno: Class Component
import { Component } from 'inferno';
class Button extends Component {
render() {
return <button>{this.props.label}</button>;
}
}
The ecosystem surrounding these libraries is a major factor in long-term maintenance.
react has the largest ecosystem. Almost every third-party UI library, tool, or tutorial supports React first. If you need a specific date picker or charting library, it likely has a React version.
preact is designed to be a drop-in replacement for React. You can often alias react to preact in your build configuration, allowing you to use thousands of existing React libraries without modification.
// preact: Aliasing for compatibility
// In webpack/vite config:
resolve: {
alias: {
'react': 'preact/compat',
'react-dom': 'preact/compat'
}
}
vue has a strong, curated ecosystem. While smaller than React's, it offers official plugins for routing (vue-router) and state management (pinia), ensuring they work seamlessly together.
svelte has a growing ecosystem. While it lacks the sheer volume of React libraries, its community produces high-quality, purpose-built tools. However, you cannot directly use React components in Svelte without wrappers.
inferno has a smaller ecosystem. While it can use some React components via compatibility layers, many modern React libraries relying on specific internal behaviors may not work perfectly. It is less suitable if you depend on a wide array of cutting-edge third-party tools.
It is important to note the current maintenance status of these packages.
react, vue, svelte, and preact are actively maintained with frequent releases and large communities.inferno is still available on npm and functional, but its development pace has slowed significantly compared to the others. It does not have a formal "deprecated" flag on npm, but its reduced community momentum means it should be chosen with caution for new, long-term projects. If you do not have a specific need for its unique performance characteristics in high-frequency trading or similar niches, react or preact are safer architectural bets.| Feature | react | vue | svelte | preact | inferno |
|---|---|---|---|---|---|
| Runtime | Virtual DOM | Virtual DOM | Compiler | Virtual DOM | Virtual DOM |
| Reactivity | Explicit Setters | Proxies | Compiler Assignment | Explicit Setters | Explicit Setters |
| Bundle Size | Medium | Medium | Small | Tiny | Tiny |
| Ecosystem | Massive | Large | Growing | Large (via alias) | Small |
| Best For | Enterprise, Jobs | Rapid Dev, All-in-one | Performance, Simplicity | Widgets, Micro-frontends | Legacy, Niche Perf |
For most professional teams starting a new project today, react remains the safest choice due to its unmatched ecosystem and hiring pool. If bundle size is a critical constraint but you need React compatibility, preact is the logical next step.
If your team values developer experience and wants a framework that feels less like managing a library and more like writing standard HTML/JS, svelte offers a compelling alternative with superior runtime performance. vue strikes a balance, offering a structured, batteries-included approach that is easier to master than React for many developers.
Reserve inferno for specific scenarios where you are optimizing an existing architecture that already relies on it, or where you have measured a distinct performance bottleneck that only Inferno's specific flags can resolve. For greenfield projects, the opportunity cost of its smaller ecosystem usually outweighs the marginal performance gains.
Choose inferno only if you are maintaining a legacy codebase that specifically depends on its unique performance optimizations for extremely high-frequency updates, such as financial trading dashboards. For new projects, it is generally recommended to evaluate react, preact, or svelte first, as Inferno's ecosystem and community momentum have slowed compared to the others.
Choose preact if you are building a widget, a micro-frontend, or an application where bundle size is critical, but you still want to use the React ecosystem and hooks. It is an excellent drop-in replacement for React when you need to shave off kilobytes without rewriting your component logic or losing access to React-compatible libraries.
Choose react if you need the largest ecosystem, extensive third-party library support, and a stable API that is the industry standard for large-scale enterprise applications. It is the best fit when hiring is a priority or when your architecture relies heavily on React Server Components and the Next.js ecosystem.
Choose svelte if your primary goal is maximum runtime performance and minimal bundle size, especially for content-heavy sites or applications running on lower-powered devices. It is suitable for developers who want to write less boilerplate code by leveraging a compiler that handles reactivity and DOM updates automatically at build time.
Choose vue if you prefer a framework that provides official solutions for routing and state management out of the box, reducing the need to evaluate third-party tools. It is ideal for teams that want a gentle learning curve with powerful features like the Composition API for complex logic reuse without the boilerplate of class-based patterns.
Inferno is an insanely fast, React-like library for building high-performance user interfaces on both the client and server.
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:
createVNode calls, instead of createElement calls.
Optimizing runtime performance of the application.
linkEvent feature removes the need to use arrow functions or binding event callbacksinferno-servercreatePortal - API<div style="background-color: red"></div> or using object literal syntax <div style={{"background-color": "red"}}></div>. For camelCase syntax support see inferno-compat.Inferno v9 requires following features to be present in the executing runtime:
PromiseString.prototype.includes()String.prototype.startsWith()Array.prototype.includes()Object.spread()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. This is due to limited support of browser versions in recent testing frameworks. https://github.com/jasmine/jasmine/blob/main/release_notes/5.0.0.md
Live examples at https://infernojs.github.io/inferno
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 completely optional, you can use hyperscript or createElement (like React does). Keep in mind that compile time optimizations are available only for JSX.
import { render } from 'inferno';
const message = 'Hello world';
render(<MyComponent message={message} />, document.getElementById('app'));
Furthermore, Inferno also uses ES6 components like React:
import { render, Component } from 'inferno';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
};
}
render() {
return (
<div>
<h1>Header!</h1>
<span>Counter is at: {this.state.counter}</span>
</div>
);
}
}
render(<MyComponent />, document.getElementById('app'));
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.
import { createTextVNode, render, Component } from 'inferno';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
};
}
_getText() {
return 'Hello!';
}
render() {
const node =
this.state.counter > 0 ? (
<div>0</div>
) : (
<span $HasTextChildren>{this._getText()}</span>
);
return (
<div>
<h1>Header!</h1>
<div $HasVNodeChildren>{node}</div>
</div>
);
}
}
render(<MyComponent />, document.getElementById('app'));
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.
import { createTextVNode, render, Component } from 'inferno';
const rootElement = document.getElementById('app');
// Start the application
render(<ExampleComponent />, rootElement);
// Tear down
render(null, rootElement);
If you have built something using Inferno you can add them here:
The easiest way to get started with Inferno is by using Create Inferno App.
Alternatively, you can try any of the following:
Core package:
npm install --save inferno
Addons:
# server-side rendering
npm install --save inferno-server
# routing
npm install --save inferno-router
Pre-bundled files for browser consumption can be found on our cdnjs:
Or on jsDelivr:
https://cdn.jsdelivr.net/npm/inferno@latest/dist/inferno.min.js
Or on unpkg.com:
https://unpkg.com/inferno@latest/dist/inferno.min.js
npm install --save-dev babel-plugin-inferno
npm install --save inferno-hyperscript
npm install --save inferno-create-element
npm install --save-dev inferno-compat
Note: Make sure you read more about inferno-compat before using it.
Inferno now has bindings available for some of the major state management libraries out there:
inferno-reduxinferno-mobx@cerebral/infernoInferno has its own JSX Babel plugin.
onClick).createRef or callback ref APIinput/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.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.
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 <input> element, in React you'd use onChange, with Inferno you'd use onInput instead (the
native DOM event is oninput).
Available synthetic events are:
onClickonDblClickonFocusInonFocusOutonKeyDownonKeyPressonKeyUponMouseDownonMouseMoveonMouseUponTouchEndonTouchMoveonTouchStartlinkEvent (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:
import { linkEvent } from 'inferno';
function handleClick(props, event) {
props.validateValue(event.target.value);
}
function MyComponent(props) {
return <div><input type="text" onClick={ linkEvent(props, handleClick) } /><div>;
}
This is an example of using it with ES2015 classes:
import { linkEvent, Component } from 'inferno';
function handleClick(instance, event) {
instance.setState({ data: event.target.value });
}
class MyComponent extends Component {
render () {
return <div><input type="text" onClick={ linkEvent(this, handleClick) } /><div>;
}
}
linkEvent() offers better performance than binding an event in a class constructor and using arrow functions, so use it where possible.
In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their own state and update it based on user input.
In Inferno, mutable state is typically kept in the state property of components, and only updated with setState().
We can combine the two by making the Inferno state be the "single source of truth". Then the Inferno component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by Inferno in this way is called a "controlled component".
render (package: inferno)import { render } from 'inferno';
render(<div />, document.getElementById('app'));
Render a virtual node into the DOM in the supplied container given the supplied virtual DOM. If the virtual node was previously rendered into the container, this will perform an update on it and only mutate the DOM as necessary, to reflect the latest Inferno virtual node.
Warning: If the container element is not empty before rendering, the content of the container will be overwritten on the initial render.
createRenderer (package: inferno)createRenderer creates an alternative render function with a signature matching that of the first argument passed to a reduce/scan function. This allows for easier integration with reactive programming libraries, like RxJS and Most.
import { createRenderer } from 'inferno';
import { scan, map } from 'most';
const renderer = createRenderer();
// NOTE: vNodes$ represents a stream of virtual DOM node updates
scan(renderer, document.getElementById('app'), vNodes$);
See inferno-most-fp-demo for an example of how to build an app architecture around this.
createElement (package: inferno-create-element)Creates an Inferno VNode using a similar API to that found with React's createElement()
import { Component, render } from 'inferno';
import { createElement } from 'inferno-create-element';
class BasicComponent extends Component {
render() {
return createElement(
'div',
{
className: 'basic',
},
createElement(
'span',
{
className: this.props.name,
},
'The title is ',
this.props.title,
),
);
}
}
render(
createElement(BasicComponent, { title: 'abc' }),
document.getElementById('app'),
);
Component (package: inferno)Class component:
import { Component } from 'inferno';
class MyComponent extends Component {
render() {
return <div>My Component</div>;
}
}
This is the base class for Inferno Components when they're defined using ES6 classes.
Functional component:
const MyComponent = ({ name, age }) => (
<span>
My name is: {name} and my age is: {age}
</span>
);
Another way of using defaultHooks.
export function Static() {
return <div>1</div>;
}
Static.defaultHooks = {
onComponentShouldUpdate() {
return false;
},
};
Default props
export function MyFunctionalComponent({ value }) {
return <div>{value}</div>;
}
MyFunctionalComponent.defaultProps = {
value: 10,
};
Functional components are first-class functions where their first argument is the props passed through from their parent.
createVNode (package: inferno)import { createVNode } from 'inferno';
createVNode(
flags,
type,
[className],
[...children],
[childFlags],
[props],
[key],
[ref],
);
createVNode is used to create html element's virtual node object. Typically createElement() (package: inferno-create-element), h() (package: inferno-hyperscript) or JSX are used to create
VNodes for Inferno, but under the hood they all use createVNode(). Below is an example of createVNode usage:
import { VNodeFlags, ChildFlags } from 'inferno-vnode-flags';
import { createVNode, createTextVNode, render } from 'inferno';
const vNode = createVNode(
VNodeFlags.HtmlElement,
'div',
'example',
createTextVNode('Hello world!'),
ChildFlags.HasVNodeChildren,
);
// <div class="example">Hello world!</div>
render(vNode, container);
createVNode arguments explained:
flags: (number) is a value from VNodeFlags, this is a numerical value that tells Inferno what the VNode describes on the page.
type: (string) is tagName for element for example 'div'
className: (string) is the class attribute ( it is separated from props because it is the most commonly used property )
children: (vNode[]|vNode) is one or array of vNodes to be added as children for this vNode
childFlags: (number) is a value from ChildFlags, this tells inferno shape of the children so normalization process can be skipped.
props: (Object) is object containing all other properties. fe: {onClick: method, 'data-attribute': 'Hello Community!}
key: (string|number) unique key within this vNodes siblings to identify it during keyed algorithm.
ref: (function) callback which is called when DOM node is added/removed from DOM.
createComponentVNode (package: 'inferno')import { createComponentVNode } from 'inferno';
createComponentVNode(flags, type, [props], [key], [ref]);
createComponentVNode is used for creating vNode for Class/Functional Component.
Example:
import { VNodeFlags, ChildFlags } from 'inferno-vnode-flags';
import {
createVNode,
createTextVNode,
createComponentVNode,
render,
} from 'inferno';
function MyComponent(props, context) {
return createVNode(
VNodeFlags.HtmlElement,
'div',
'example',
createTextVNode(props.greeting),
ChildFlags.HasVNodeChildren,
);
}
const vNode = createComponentVNode(
VNodeFlags.ComponentFunction,
MyComponent,
{
greeting: 'Hello Community!',
},
null,
{
onComponentDidMount() {
console.log('example of did mount hook!');
},
},
);
// <div class="example">Hello Community!</div>
render(vNode, container);
createComponentVNode arguments explained:
flags: (number) is a value from VNodeFlags, this is a numerical value that tells Inferno what the VNode describes on the page.
type: (Function/Class) is the class or function prototype for Component
props: (Object) properties passed to Component, can be anything
key: (string|number) unique key within this vNodes siblings to identify it during keyed algorithm.
ref: (Function|Object) this property is object for Functional Components defining all its lifecycle methods. For class Components this is function callback for ref.
createTextVNode (package: 'inferno')createTextVNode is used for creating vNode for text nodes.
createTextVNode arguments explained:
text: (string) is a value for text node to be created.
key: (string|number) unique key within this vNodes siblings to identify it during keyed algorithm.
import { createTextVNode } from 'inferno';
createTextVNode(text, key);
cloneVNode (package: inferno-clone-vnode)This package has same API as React.cloneElement
import { cloneVNode } from 'inferno-clone-vnode';
cloneVNode(vNode, [props], [...children]);
Clone and return a new Inferno VNode using a VNode as the starting point. The resulting VNode will have the original VNode's props with the new props merged in shallowly. New children will replace existing children. key and ref from the original VNode will be preserved.
cloneVNode() is almost equivalent to:
<VNode.type {...VNode.props} {...props}>
{children}
</VNode.type>
An example of using cloneVNode:
import { createVNode, render } from 'inferno';
import { cloneVNode } from 'inferno-clone-vnode';
import { VNodeFlags } from 'inferno-vnode-flags';
const vNode = createVNode(
VNodeFlags.HtmlElement,
'div',
'example',
'Hello world!',
);
const newVNode = cloneVNode(vNode, { id: 'new' }); // we are adding an id prop to the VNode
render(newVNode, container);
If you're using JSX:
import { render } from 'inferno';
import { cloneVNode } from 'inferno-clone-vnode';
const vNode = <div className="example">Hello world</div>;
const newVNode = cloneVNode(vNode, { id: 'new' }); // we are adding an id prop to the VNode
render(newVNode, container);
createPortal (package: 'inferno')HTML:
<div id="root"></div>
<div id="outside"></div>
Javascript:
const { render, Component, version, createPortal } from 'inferno';
function Outsider(props) {
return <div>{`Hello ${props.name}!`}</div>;
}
const outsideDiv = document.getElementById('outside');
const rootDiv = document.getElementById('root');
function App() {
return (
<div>
Main view
...
{createPortal(<Outsider name="Inferno" />, outsideDiv)}
</div>
);
}
// render an instance of Clock into <body>:
render(<App />, rootDiv);
Results into:
<div id="root">
<div>Main view ...</div>
</div>
<div id="outside">
<div>Hello Inferno!</div>
</div>
Cool, huh? Updates (props/context) will flow into "Outsider" component from the App component the same way as any other Component. For inspiration on how to use it click here!
createRef (package: inferno)createRef API provides shorter syntax than callback ref when timing of element is not needed.
import { Component, render, createRef } from 'inferno';
class Foobar extends Component {
constructor(props) {
super(props);
// Store reference somewhere
this.element = createRef(); // Returns object {current: null}
}
render() {
return (
<div>
<span id="span" ref={this.element}>
Ok
</span>
</div>
);
}
}
render(<Foobar />, container);
createFragment (package: inferno)createFragment is the native way to createFragment vNode. createFragment(children: any, childFlags: ChildFlags, key?: string | number | null)
createFragment arguments explained:
children: (Array) Content of fragment vNode, typically array of VNodes
childFlags: (number) is a value from ChildFlags, this tells inferno shape of the children so normalization process can be skipped.
key: (string|number) unique key within this vNodes siblings to identify it during keyed algorithm.
Alternative ways to create fragment vNode are:
<> ... </>, <Fragment> .... </Fragment> or <Inferno.Fragment> ... </Inferno.Fragment>createElement(Inferno.Fragment, {key: 'test'}, ...children)h(Inferno.Fragment, {key: 'test'}, children)In the below example both fragments are identical except they have different key
import { Fragment, render, createFragment } from 'inferno';
import { ChildFlags } from 'inferno-vnode-flags';
function Foobar() {
return (
<div $HasKeyedChildren>
{createFragment(
[<div>Ok</div>, <span>1</span>],
ChildFlags.HasNonKeyedChildren,
'key1',
)}
<Fragment key="key2">
<div>Ok</div>
<span>1</span>
</Fragment>
</div>
);
}
render(<Foobar />, container);
forwardRef (package: inferno)forwardRef is a new mechanism to "forward" ref inside a functional Component. It can be useful if you have simple functional Components and you want to create reference to a specific element inside it.
import { forwardRef, Component, render } from 'inferno';
const FancyButton = forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
class Hello extends Component {
render() {
return (
<FancyButton
ref={(btn) => {
if (btn) {
// btn variable is the button rendered from FancyButton
}
}}
>
Click me!
</FancyButton>
);
}
}
render(<Hello />, container);
hydrate (package: inferno-hydrate)import { hydrate } from 'inferno-hydrate';
hydrate(<div />, document.getElementById('app'));
Same as render(), but is used to hydrate a container whose HTML contents were rendered by inferno-server. Inferno will attempt to attach event listeners to the existing markup.
findDOMNode (package: inferno-extras)This feature has been moved from inferno to inferno-compat in v6. No options are needed anymore.
Note: we recommend using a ref callback on a component to find its instance, rather than using findDOMNode(). findDOMNode() cannot be used on functional components.
If a component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.
In most cases, you can attach a ref to the DOM node and avoid using findDOMNode() at all. When render returns null or false, findDOMNode() returns null.
If Component has rendered fragment it returns the first element.
VNodeFlags:
VNodeFlags.HtmlElementVNodeFlags.ComponentUnknownVNodeFlags.ComponentClassVNodeFlags.ComponentFunctionVNodeFlags.TextVNodeFlags.SvgElementVNodeFlags.InputElementVNodeFlags.TextareaElementVNodeFlags.SelectElementVNodeFlags.PortalVNodeFlags.ReCreate (JSX $ReCreate) always re-creates the vNodeVNodeFlags.ContentEditableVNodeFlags.FragmentVNodeFlags.InUseVnodeFlags.ForwardRefVNodeFlags.NormalizedVNodeFlags Masks:
VNodeFlags.ForwardRefComponent Functional component wrapped in forward refVNodeFlags.FormElement - Is form elementVNodeFlags.Element - Is vNode elementVNodeFlags.Component - Is vNode ComponentVNodeFlags.DOMRef - Bit set when vNode holds DOM referenceVNodeFlags.InUseOrNormalized - VNode is used somewhere else or came from normalization processVNodeFlags.ClearInUseNormalized - Opposite mask of InUse or NormalizedChildFlags
ChildFlags.UnknownChildren needs NormalizationChildFlags.HasInvalidChildren is invalid (null, undefined, false, true)ChildFlags.HasVNodeChildren (JSX $HasVNodeChildren) is single vNode (Element/Component)ChildFlags.HasNonKeyedChildren (JSX $HasNonKeyedChildren) is Array of vNodes non keyed (no nesting, no holes)ChildFlags.HasKeyedChildren (JSX $HasKeyedChildren) is Array of vNodes keyed (no nesting, no holes)ChildFlags.HasTextChildren (JSX $HasTextChildren) vNode contains only textChildFlags Masks
ChildFlags.MultipleChildren Is ArrayrenderToString (package: inferno-server)import { renderToString } from 'inferno-server';
const string = renderToString(<div />);
Render a virtual node into an HTML string, given the supplied virtual DOM.
| Name | Triggered when | Arguments to callback |
|---|---|---|
onComponentWillMount | a functional component is about to mount | |
onComponentDidMount | a functional component has mounted successfully | domNode |
onComponentShouldUpdate | a functional component has been triggered to update | lastProps, nextProps |
onComponentWillUpdate | a functional component is about to perform an update | lastProps, nextProps |
onComponentDidUpdate | a functional component has performed an update | lastProps, nextProps |
onComponentWillUnmount | a functional component is about to be unmounted | domNode |
onComponentDidAppear | a functional component has mounted and is ready for animations | domNode, props |
onComponentWillDisappear | a functional component is unmounted before DOM node is removed | domNode, props, callback |
onComponentWillDisappear has special type of argument "callback" which needs to be called when component is ready to be removed from the DOM. fe. after animations are finished.
All these Component lifecycle methods ( including render and setState - callback) are called with Component instance context. You don't need to "bind" these methods.
| Name | Triggered when | Arguments to callback |
|---|---|---|
componentDidMount | component has been mounted successfully | |
componentWillMount | component is about to mount | |
componentWillReceiveProps | before render when component updates | nextProps, context |
shouldComponentUpdate | component has been triggered to update | nextProps, nextState |
componentWillUpdate | component is about to perform an update | nextProps, nextState, context |
componentDidUpdate | component has performed an update | lastProps, lastState, snapshot |
componentWillUnmount | component is about to be unmounted | |
getChildContext | before render method, return value object is combined to sub tree context | |
getSnapshotBeforeUpdate | before component updates, return value is sent to componentDidUpdate as 3rd parameter | lastProps, lastState |
static getDerivedStateFromProps | before render method | nextProps, state |
componentDidAppear | component has mounted and is ready for animations | domNode |
componentWillDisappear | component is unmounted before DOM node is removed | domNode, callback |
componentWillDisappear has special type of argument "callback" which needs to be called when component is ready to be removed from the DOM. fe. after animations are finished.
Functional lifecycle events must be explicitly assigned via props onto a functional component like shown below:
import { render } from 'inferno';
function mounted(domNode) {
// [domNode] will be available for DOM nodes and components (if the component has mounted to the DOM)
}
function FunctionalComponent({ props }) {
return <div>Hello world</div>;
}
render(
<FunctionalComponent onComponentDidMount={mounted} />,
document.getElementById('app'),
);
Please note: class components (ES2015 classes) from inferno do not support the same lifecycle events (they have their own lifecycle events that work as methods on the class itself).
By default, Inferno will run in development mode. Development mode provides extra checks and better error messages at the cost of slower performance and larger code to parse. When using Inferno in a production environment, it is highly recommended that you turn off development mode.
Ensure the environment variable process.env.NODE_ENV is set to production.
When building your application bundle, ensure process.env.NODE_ENV is replaced with string"development" or "production" based on the workflow.
It is recommended to use ts-plugin-inferno for typescript TSX compilation and babel-plugin-infeno for javascript JSX compilation.
When building for development, you may want to use inferno.dev.mjs for v9 or newer and inferno.dev.esm.js for older than v9. That bundle file contains ES6 exports for better tree-shaking support, improved error messages and added validation to help fixing possible issues during development.
The file is found from package.json - dev:module entry point and the files are physically located in node_modules/inferno/dist/ folder.
Remember that it is not recommended to use that file in production due to slower performance. For production usage use node_modules/inferno/dist/inferno.mjs -file for v9 or newer and node_modules/inferno/dist/inferno.esm.js -file for older than v9.
Example of Webpack configuration:
const path = require('path');
const infernoTsx = require('ts-plugin-inferno').default;
... webpack config ...
module: {
rules: [
{
test: /\.js$/, // Add "jsx" if your application uses `jsx` file extensions
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
options: {
plugins: [
// Compile javascript JSX syntax using inferno's own plugin
['babel-plugin-inferno', {imports: true}]
]
}
}]
},
{
test: /\.ts+(|x)$/, // Compile ts and tsx extensions
exclude: /node_modules/,
use: [{
loader: 'ts-loader',
options: {
getCustomTransformers: () => ({
// inferno custom TSX plugin
after: [infernoTsx()]
}),
compilerOptions: {
/* typescript compiler options */
}
}
}]
}
]
},
resolve: {
extensions: ['.js', '.ts', '.tsx'],
alias: {
// This maps import "inferno" to es6 module entry based on workflow
inferno: path.resolve(__dirname, 'node_modules/inferno/dist', isProduction ? 'index.dev.mjs' : 'index.mjs')
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(isProduction ? 'production' : 'development')
}
})
]
Example of Rollup configuration:
const path = require('path');
const alias = require('@rollup/plugin-alias');
const {babel} = require('@rollup/plugin-babel');
const replace = require('@rollup/plugin-replace');
const typescript = require('rollup-plugin-typescript2');
const transformInferno = require('ts-plugin-inferno').default;
... Rollup config ...
{
input: /* entry file */,
plugins: [
alias({
resolve: ['.js'],
entries: [
// This maps import "inferno" to es6 module entry based on workflow
{find: 'inferno', replacement: path.resolve(__dirname, 'node_modules/inferno/dist', isProduction ? 'index.dev.mjs' : 'index.mjs')}
]
}),
typescript({
include: ['*.ts+(|x)', '**/*.ts+(|x)'],
transformers: [
() => ({
after: [transformInferno()]
})
],
tsconfig: 'tsconfig.json',
tsconfigOverride: {
/* typescript compiler options */
}
}),
babel({
babelrc: false,
sourceMaps: isDeploy,
plugins: [
// Compile javascript JSX syntax using inferno's own plugin
['babel-plugin-inferno', {imports: true}]
],
babelHelpers: 'bundled'
})
]
}
Inferno always wants to deliver great performance. In order to do so, it has to make intelligent assumptions about the state of the DOM and the elements available to mutate. Custom namespaces conflict with this idea and change the schema of how different elements and attributes might work, so Inferno makes no attempt to support namespaces. Instead, SVG namespaces are automatically applied to elements and attributes based on their tag name.
If you want to contribute code, fork this project and submit a PR from your fork. To run browser tests you need to build the repos. A complete rebuild of the repos can take >5 mins.
$ git clone git@github.com:infernojs/inferno.git
$ cd inferno && npm i
$ npm run test:node
$ npm run build
$ npm run test:browser
If you only want to run the browser tests when coding, use the following to reduce turnaround by 50-80%:
$ npm run quick-test:browser # Compiles all packages and runs browser tests
$ npm run quick-test:browser-inferno # Only compiles the inferno package and runs browser tests
$ npm run quick-test:browser-debug # Compiles all packages and runs browser tests with "debug"
There is an InfernoJS Discord. You can join via https://discord.gg/SUKuhgaBpF.
This project exists thanks to all the people who contribute. [Contribute].
Thank you to all our backers! π [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]