What’s new in Preact X?
Tags: react, javascript, preact
Published: 2019-12-14 18:12:57

---
title: What’s new in Preact X?
published: true
date: 2019-12-13 14:50:39 UTC
tags: react,javascript,preact
canonical_url: https://blog.logrocket.com/whats-new-in-preact-x/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/ffo9joco4ay40469ptr1.png
---
**Written by [Ogundipe Samuel](https://blog.logrocket.com/author/osamuel/)**✏️

Preact is a JavaScript library that describes itself as a [fast 3kB alternative to React](https://blog.logrocket.com/introduction-to-preact-a-smaller-faster-react-alternative-ad5532eb6d79/) with the same modern API. It has one of the fastest virtual DOM libraries compared to similar frameworks. You can start writing Preact in your React/ReactDOM code without any changes to your workflow or codebase.

With over 24,000 ️stars on [GitHub](https://github.com/preactjs/preact/releases) and a host of dedicated community members constantly providing support, it has never been easier to build highly efficient, small, performant, blazing fast frontend applications in JS.

Since its initial release, Preact’s maintainers have published several versions to address issues and add features. In October, Preact X rolled out with several updates designed to solve common pain points and improve existing features.

Let’s go over some of the recent changes and discuss how they can help us develop better applications using PreactJS.

N.B., this tutorial assumes a basic understanding of PreactJS or ReactJS. To learn more about Preact, read the library’s [official guide](https://preactjs.com/guide/v10/getting-started/).

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## New capabilities and improvements in Preact X

Preact’s maintainers have added major improvements to support many of the latest React features. Let’s review some of the most interesting new capabilities.

### Fragments

Fragments let you group lists of children without adding extra nodes to the DOM because they are not rendered to the DOM. You can employ this feature where you would normally use a wrapper `div`. It’s most useful when working with lists, tables, or CSS flexbox.

Consider the following markup:

```jsx
class Table extends Component {
  render() {
    return (
      <table>
        <tr>
          <Columns />
        </tr>
      </table>
    );
  }
}
class Columns extends Component {
  render() {
    return (
      <div>
        <td>One</td>
        <td>Two</td>
      </div>
    );
  }
} 
```

The rendered result will be invalid HTML because the wrapper `div` from the `Columns` component is rendered inside the `<tr>` in the `Table` component.

With fragments, you can render outputs on the DOM without adding any extra elements.

```jsx
class Columns extends Component {
  render() {
    return (
      <>
        <td>One</td>
        <td>Two</td>
      </>
    );
  }
} 
```

Now, the output will be valid HTML, because no extra `div` is added to the DOM. Fragments can be written in two ways:

```jsx
BY :
import { Fragment, render } from 'preact';

function TodoItems() {
  return (
    <Fragment>
        <li>A</li>
        <li>B</li>
        <li>C</li>
    </Fragment>
  )
}

or 

function TodoItems() {
  return (
    <>
        <li>A</li>
        <li>B</li>
        <li>C</li>
    </>
  )
}
```

To learn more, read the [Components](https://preactjs.com/guide/v10/components/#fragments) article in the official Preact X guide.

### Hooks

Hooks are an alternative to the class-based component API. Hooks allow you to compose state and stateful logic and easily reuse them between components. Preact X offers a lot of hooks out of the box as well as the ability to create custom hooks. You can import hooks from `preact/hooks` or `preact/compat`.

```jsx
import {useState, useCallback} from 'preact/hooks';
or
import {useState, useCallback} from 'preact/compat';

function Counter() {
  const [value, setValue] = useState(0);
  const increment = useCallback(() => setValue(value + 1), [value]);

  return (
    <div>
      Counter: {value}
      <button onClick={increment}>Increment</button>
    </div>
  );
}
```

The above code is a counter component that increments in value when clicked. It utilizes the `useState` and `useCallback` hooks provided in the Preact X API. As shown, the code is also the same as you would write in React.

N.B., [hooks](https://preactjs.com/guide/v10/hooks/) are optional and can be used alongside class components.

### componentDidCatch

Preact X includes an update to the `componentDidCatch` lifecycle method, which is called after your component renders. This allows you to handle any errors that happen during rendering, including errors that happen in a lifecycle hook but excluding any asynchronously thrown errors, such as after a `fetch()` call. When an error is caught, you can use this lifecycle to react to any errors and display a nice error message or any other fallback content.

```jsx
class Catcher extends Component {
  state = { errored: false }

  componentDidCatch(error) {
    this.setState({ errored: true });
  }

  render(props, state) {
    if (state.errored) {
      return <p>Something went badly wrong</p>;
    }
    return props.children;
  }
}
```

In the above code, we call the `componentDidCatch()`, which is invoked as soon as the component is rendered. If an error is caught, you can update your component to let users know an error occurred and log entries to logging services.

This ensures a much cleaner codebase and an even easier error tracking. The [official guide](https://preactjs.com/guide/v10/components/#componentdidcatch) has more information about `componentDidCatch()`.

### createContext

Context provides a way to pass data through the component tree without having to pass props down manually at every level. Although context is not new to Preact, the legacy API `getChildContext()` is known to have issues when delivering updates deeper down the virtual DOM tree.

A context object is created via the `createContext(initialValue)` function. It returns a `Provider` component that is used to set the context value and a `Consumer` one that retrieves the value from the context.

```jsx
import {useContext} from 'preact/compat';

const Theme = createContext('light');

function DisplayTheme() {
  const theme = useContext(Theme);
  return <p>Active theme: {theme}</p>;
}

// ...later
function App() {
  return (
    <Theme.Provider value="light">
      <OtherComponent>
        <DisplayTheme />
      </OtherComponent>
    </Theme.Provider>
  )
}
```

## Changes to Preact core

Previously, `preact-compat` was included as a separate package. It is now included in the same package as Preact itself; there’s nothing extra to install to use libraries from the React ecosystem.

```jsx
// Preact 8.x
import React from "preact-compat";

// Preact X
import React from "preact/compat";
```

Preact X also now directly supports [CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) for styling Preact components. The Preact team specifically made sure to include several popular packages in the testing process to guarantee full support for them.

## Conclusion

In this tutorial, we explored some features introduced in Preact X. To see a concrete list of all the changes and learn more about the new releases, be sure to check out the [Preact release page on GitHub](https://github.com/preactjs/preact/releases).

What is your favorite new feature or API? Feel free to share your thoughts in the comments.

## Ensure Your production React app renders properly

Debugging React applications can be difficult, especially when there is complex state. If you’re interested in monitoring and tracking Redux state, network requests, JavaScript errrors, component load time, and much more for all of your users in production, [try LogRocket](https://logrocket.com/signup/). [![](https://i1.wp.com/files.readme.io/27c94e7-Image_2017-06-05_at_9.46.04_PM.png?ssl=1)](https://logrocket.com/signup/)[![LogRocket Dashboard Free Trial Banner](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)](https://logrocket.com/signup/)[https://logrocket.com/signup/](https://logrocket.com/signup/)

[LogRocket](https://logrocket.com/signup/) is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps – [Start monitoring for free](https://logrocket.com/signup/).
* * *
The post [What’s new in Preact X?](https://blog.logrocket.com/whats-new-in-preact-x/) appeared first on [LogRocket Blog](https://blog.logrocket.com).