DEV Community

Cover image for What’s new in Preact X?
Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

What’s new in Preact X?

Written by Ogundipe Samuel✏️

Preact is a JavaScript library that describes itself as a fast 3kB alternative to React 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 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.

LogRocket Free Trial Banner

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:

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>
    );
  }
} 
Enter fullscreen mode Exit fullscreen mode

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.

class Columns extends Component {
  render() {
    return (
      <>
        <td>One</td>
        <td>Two</td>
      </>
    );
  }
} 
Enter fullscreen mode Exit fullscreen mode

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

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>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

To learn more, read the Components 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.

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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 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.

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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 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.

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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.

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

// Preact X
import React from "preact/compat";
Enter fullscreen mode Exit fullscreen mode

Preact X also now directly supports CSS custom properties 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.

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. LogRocket Dashboard Free Trial Bannerhttps://logrocket.com/signup/

LogRocket 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.


The post What’s new in Preact X? appeared first on LogRocket Blog.

Top comments (0)