Replacing React with Preact

Preact is a fast 3kB alternative to React with the same modern API

#Stacks (Source Code)

#Build (gzip size)

HTML0.29 kB
CSS1.56 kB
JavaScript8.57 kB
Total10.43 kB

#Core Libraries

Preact is not intended to be a reimplementation of React. There are differences. Many of these differences are trivial, or can be completely removed by using preact/compat, which is a thin layer over Preact that attempts to achieve 100% compatibility with React.

#Resources

#Basic Usage

Preact is a tiny React alternative. And It works well with most libraries of the React ecosystem which built on the top of React Hooks.

With universal CLI such as Vite, preact support is out of the box.

And if from an existing project, you can also easily replace React with Preact to reduce app's build size in minitus.

// * ---------------- Replacing import using preact (or by setting alias)

// import { render } from "react-dom";
import { render } from "preact";

// import type { FC } from "react";
import type { FunctionalComponent as FC } from "preact";

// import { createContext, useContext, useState } from "react";
import { createContext, useContext, useState } from "preact/compat";

// * ---------------- and tweak your build config

// * e.g. vite has preact support out of the box

import preact from "@preact/preset-vite";
import { defineConfig } from "vite";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [preact()],
});

// * ---------------- tsconfig.json

const tsconfigJson = {
  compilerOptions: {
    jsx: "preserve",
    jsxFactory: "h",
    jsxFragmentFactory: "Fragment",
  },
};