useQueryParams – A React Hook for managing state in URL query parameters

Once you’ve set up a QueryParamProvider high up your component tree, you can start using useQueryParam to get (and set) querystring parameters

import * as React from 'react';
import { useQueryParam, NumberParam, StringParam } from 'use-query-params';

const UseQueryParamExample = () => {
  // something like: ?x=123&foo=bar in the URL
  const [num, setNum] = useQueryParam('x', NumberParam);
  const [foo, setFoo] = useQueryParam('foo', StringParam);

  return (
    <div>
      <h1>num is {num}</h1>
      <button onClick={() => setNum(Math.random())}>Change</button>
      <h1>foo is {foo}</h1>
      <button onClick={() => setFoo(`str${Math.random()}`)}>Change</button>
    </div>
  );
};

export default UseQueryParamExample;

Also ships with an HOC and Render Props approaches.

useQueryParams

Recoil – An Experimental State Management Library for React

Recoil is the State Management Library for React they use at Facebook.

Recoil lets you create a data-flow graph that flows from atoms (shared state) through selectors (pure functions) and down into your React components. Atoms are units of state that components can subscribe to. Selectors transform this state either synchronously or asynchronously

Best to watch the talk from React Europe 2020 embedded above. It clearly explains why Recoil come to exist, and when & how to use it.

If you’ve ever used MobX it might all sound a bit familiar. This Twitter Thread by the MobX author is worth a quick read.

Recoil →

Remix – React Framework for Web Apps

The past few weeks I’ve been enjoying the newsletter of Remix, an yet to be released React Framework

Remix is a web application framework for React from the authors of React Router: Michael Jackson and Ryan Florence. It provides APIs and conventions for server rendering, data loading, routing and more.

You can also read some of its details in their introductory post from two weeks ago. I really like this post, as they build up their code examples in a step-by-step manner. In that post they cover their approach to:

  • File System Routing
  • Data Loading
  • Location-Based Cache
  • Meta Tags and Document Titles

Remix will be a paid product. Next to a Commercial License they’ll also provide an Affordable Indie License.

Remix →
Remix Preview #1 →

useWorker() – Use Web Workers with React Hooks

useWorker() is a js library (with typescript support) that allows you to use the Web Worker Web API, through React Hooks. This library allows you to run the expensive function without blocking the user interface, using a simple syntax that makes use of Promise

import React from "react";
import { useWorker, WORKER_STATUS } from "@koale/useworker";

const numbers = [...Array(5000000)].map(e => ~~(Math.random() * 1000000));
const sortNumbers = nums => nums.sort();

const Example = () => {
  const [sortWorker, { status, kill }] = useWorker(sortNumbers);
  const runSort = async () => {
    const result = await sortWorker(numbers); // non-blocking UI
    console.log("End.");
  };
  return (<button type="button" onClick={runSort}> Run Sort</button>);
};

Installation per NPM/Yarn:

npm install --save @koale/useworker

useWorker()
useWorker() Source (GitHub) →

🤔 Unfamiliar with Web Workers? Check out Handling JavaScript events with Web Workers then!

Use Tailwind classes within any CSS-in-JS library with Twin

To use Tailwind – or any prebuilt CSS library/framework for that matter – in a React app you can simply import its generated CSS file and use the classes it exposes:

import '../tailwind.generated.css';

// …

const Alert = ({ title = '', message }) => (
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
        {title && <strong class="font-bold">{title}</strong>}
        <span class="block sm:inline">{message}</span>
        <span class="absolute top-0 bottom-0 right-0 px-4 py-3">
            <svg class="fill-current h-6 w-6 text-red-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                <title>Close</title>
                <path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z" />
            </svg>
        </span>
    </div>
);

But what if you want to combine Tailwind with 💅 styled-components or 👩‍🎤 emotion? This is where Twin comes in handy:

import React from 'react'
import tw from 'twin.macro'
import styled from '@emotion/styled/macro'
import { css } from '@emotion/core'

const Input = styled.input`
  ${tw`border`}
  ${({ hasHover }) => hasHover && tw`hover:border-black`}
  color: white;
`
export default () => <Input hasHover />

tw will extract the styles from the classes so that the CSS-in-JS Library can use it.

twin.macro →

💡 To work with CSS Class Names in React you can use the classnames package or an implementation on top of it such as classnames-components. I personally prefer one of these methods as these packages allow me to still write my CSS in CSS … #separationofconcerns #embracetheplatform

React Performance Optimization with React.memo()

I know I’ve posted a similar article before but this is a pitfall I commonly see and therefore it can’t be repeated enough.

React internally already optimizes the performance quite a bit without having to explicitly optimize for performance. React.memo can help you to optimize the number of renders of your React components even further.

In this article I will explain to you how you can optimize React performance by using React.memo, some common pitfalls you could encounter and why you shouldn’t always use React.memo.

React Performance Optimization with React.memo()

Rebuilding our tech stack for the new Facebook.com

The Facebook Engineering Team on how they’ve built the new Facebook.com – a version which I’ve been able to try for nearly two months by now.

Throughout the process, we anchored our work around two technical mantras:

  1. As little as possible, as early as possible. We should deliver only the resources we need, and we should strive to have them arrive right before we need them.
  2. Engineering experience in service of user experience. The end goal of our development is all about the people using our website. As we think about the UX challenges on our site, we can adapt the experience to guide engineers to do the right thing by default.

We applied these same principles to improve four main elements of the site: CSS, JavaScript, data, and navigation.

Rebuilding our tech stack for the new Facebook.com →

🤔 A bit weird they named the CSS section “Rethinking CSS to unlock new capabilities” though, as they’re basically using CSS as it is meant to be used: use em for font-sizes so that users can zoom, use CSS Custom Properties for theming / dark mode, etc. #embracetheplatform

Second-guessing the modern web

An article that’s been making rounds on Twitter today is Second-guessing the modern web:

There is a sweet spot of React: in moderately interactive interfaces. Complex forms that require immediate feedback, UIs that need to move around and react instantly. That’s where it excels.

But there’s a lot on either side of that sweet spot.

The low performance parts don’t need to be React. Listing pages, static pages, blogs – these things are increasingly built in React, but the benefits they accrue are extremely narrow. A lot of the optimizations that are cropping up in these corners, things like bundle splitting, server-side rendering, and prerendering, are triangulating, essentially, what we had before the rise of React.

If you’re swinging the React hammer, everything looks like a <Nail />. A smart developer knows when to use it, and when not to use it.

But what if you didn’t have to choose? As Dan Abramov from the React team tweeted (be sure to read the whole thread):

This proposed approach goes beyond Zeit’s Vercel’s Next.js file based routing and hits more close to Inertia.js.

Second-guessing the modern web →

Using React’s Key Attribute to remount a Component

Nik Graf details a little trick I also use from time to time: changing the key of a React component to force remount it.

Upon clicking a contact in the list, the active contact’s id is used as the key for the Detail component.

<Detail key={activeContact.id} contact={activeContact} />

Using React’s Key Attribute to remount a Component →

useImmer – A React Hook to use Immer to manipulate state

useImmer(initialState) is very similar to useState. The function returns a tuple, the first value of the tuple is the current state, the second is the updater function, which accepts an immer producer function, in which the draft can be mutated freely, until the producer ends and the changes will be made immutable and become the next state.

import React from "react";
import { useImmer } from "use-immer";


function App() {
  const [person, updatePerson] = useImmer({
    name: "Michel",
    age: 33
  });

  function updateName(name) {
    updatePerson(draft => {
      draft.name = name;
    });
  }

  function becomeOlder() {
    updatePerson(draft => {
      draft.age++;
    });
  }

  return (
    <div className="App">
      <h1>
        Hello {person.name} ({person.age})
      </h1>
      <input
        onChange={e => {
          updateName(e.target.value);
        }}
        value={person.name}
      />
      <br />
      <button onClick={becomeOlder}>Older</button>
    </div>
  );
}

Also comes with an useImmerReducer Hook.

use-immer →

Related: The previously linked Mutik also uses Immer under the hood.