npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-facade

v0.5.0

Published

A simple library that uses Proxy and TypeScript to create a strongly typed facade for your React hooks.

Downloads

2,698

Readme

React Facade

Write components with placeholders for hooks.

An experimental 2kb library that uses Proxy and TypeScript to create a strongly typed facade for your React hooks.

  • Dependency inversion between components and hooks: Build components that rely on hooks that do not have a particular implementation.
  • Works with all of your existing hooks: Extract hooks to the top level of your program and replace them with a facade.
  • Simplified component testing: You were already testing your hooks anyway (right?), so why test them again? Focus on rendering outcomes rather than bungling around with a cumbersome setup for test cases.

The hooks implementation is injected via React context so that they can be changed between views or testing. It is dependency injection for hooks that does not require higher-order functions/Components.

Example

Consider an application which describes its data-fetching layer in the UI with the following list of hooks,

function useCurrentUser(): User;
function usePostById(id: string): { loading: boolean; error?: Error; data?: Post };
function useCreateNewPost(): (postData: PostData) => Promise<Post>;
// etc...

Given this interface, a developer can reliably use these hooks without knowing anything about their underlying implementation (leaving aside questions of fidelity). That is to say: the developer only cares about the interface. The problem, however, is that by inlining a hook as part of the React component, the implementation cannot be ignored. For example, a component UserProfile may have the following definition,

// user-profile.tsx

import React from "react";
import { userCurrentUser } from "./hooks";

export function UserProfile() {
  const user = useCurrentUser();

  // ... render user profile
}

The developer of this component may not care about the implementation of useCurrentUser, but the tests sure do! If under the hood useCurrentUser calls the react-redux useSelector, then UserProfile depends directly on a global Redux store. Moreover, any component using UserProfile also has this dependency. The coupling between the store and component tree is hard-coded by this hook. Yikes!

Consider the same problem where the implementation can be completely ignored and replaced by dependency injection. We define the same interface using createFacade,

// facade.ts

import { createFacade } from "react-facade";

type Hooks = {
  useCurrentUser(): User;
  usePostById(id: string): { loading?: boolean; error?: Error; data?: Post };
  useCreateNewPost(): (postData: PostData) => Promise<Post>;
  // ...
};

// no implementation!
export const [hooks, ImplementationProvider] = createFacade<Hooks>();

And then the UserProfile becomes,

// user-profile.tsx

import React from "react";
import { hooks } from "./facade";

export function UserProfile() {
  const user = hooks.useCurrentUser();

  // ... render user profile
}

This time, we don't care about the implementation because there literally isn't one. Depending on the environment, it can be injected by passing a different implementation to ImplementationProvider.

At the application level, we might use useSelector to fetch the current user from our store,

// app.tsx

import React from "react";
import { useSelector } from "react-redux";
import { ImplementationProvider } from "./facade";
// ...

const implementation = {
  useCurrentUser(): User {
    return useSelector(getCurrentUser);
  },

  // ...
};

return (
  <ImplementationProvider implementation={implementation}>
    <UserProfile />
  </ImplementationProvider>
);

While in a test environment, we can return a stub user so long as it matches our interface,

// user-profile.test.tsx

import React from "react";
import { render } from "@testing-library/react";
import { ImplementationProvider } from "./facade";
// ...

test("some thing", () => {
  const implementation = {
    useCurrentUser(): User {
      return {
        id: "stub",
        name: "Gabe",
        // ...
      };
    },

    // ...
  };

  const result = render(
    // What is `__UNSAFE_Test_Partial`? See API section
    <ImplementationProvider.__UNSAFE_Test_Partial implementation={implementation}>
      <UserProfile />
    </ImplementationProvider.__UNSAFE_Test_Partial>
  );

  // ...
});

We are programming purely toward the interface and NOT the implementation!

Again, consider how this might simplify testing a component that relied on this hook,

function usePostById(id: string): { loading: boolean; error?: Error; data?: Post };

Testing different states is simply a matter of declaratively passing in the right one,

// post.test.tsx

const loadingImplementation = {
  usePostById(id: string) {
    return {
      loading: true,
    };
  },
};

const errorImplementation = {
  usePostById(id: string) {
    return {
      loading: false,
      error: new Error("uh oh!"),
    };
  },
};

// ...

test("shows the loading spinner", () => {
  const result = render(
    <ImplementationProvider.__UNSAFE_Test_Partial implementation={loadingImplementation}>
      <Post id={id} />
    </ImplementationProvider.__UNSAFE_Test_Partial>
  );

  // ...
});

test("displays an error", () => {
  const result = render(
    <ImplementationProvider.__UNSAFE_Test_Partial implementation={errorImplementation}>
      <Post id={id} />
    </ImplementationProvider.__UNSAFE_Test_Partial>
  );

  // ...
});

API

createFacade

type Wrapper = React.JSXElementConstructor<{ children: React.ReactElement }>;

function createFacade<T>(
  options?: Partial<{ displayName: string; strict: boolean; wrapper: Wrapper }>
): [Proxy<T>, ImplementationProvider<T>];

Takes a type definition T - which must be an object where each member is a function - and returns the tuple of the interface T (via a Proxy) and an ImplementationProvider. The developer provides the real implementation of the interface through the Provider.

The ImplementationProvider does not collide with other ImplementationProviders created by other createFacade calls, so you can make as many of these as you need.

Options

| option | type | default | details | | ----------- | -------- | -------------------------- | ------------------------------------------------------------------------ | | displayName | string | "Facade" | The displayName for debugging with React Devtools . | | strict | boolean | true | When true does not allow the implementation to change between renders. | | wrapper | React.FC | ({ children }) => children | A wrapper component that can be used to wrap the ImplementationProvider. |

ImplementationProvider<T>

Accepts a prop implementation: T that implements the interface defined in createFacade<T>().

const implementation = {
  useCurrentUser(): User {
    return useSelector(getCurrentUser);
  },

  // ...
};

return (
  <ImplementationProvider implementation={implementation}>
    <UserProfile />
  </ImplementationProvider>
);

ImplementationProvider<T>.__UNSAFE_Test_Partial

Used for partially implementing the interface when you don't need to implement the whole thing but still want it to type-check (tests?). For the love of God, please do not use this outside of tests...

<ImplementationProvider.__UNSAFE_Test_Partial implementation={partialImplementation}>
  <UserProfile />
</ImplementationProvider.__UNSAFE_Test_Partial>

Installing

npm install react-facade

Asked Questions

Why not just use jest.mock?

Mocking at the module level has the notable downside that type safety is optional. The onus is on the developer to ensure that the mock matches the actual interface. While stubbing with a static language is dangerous enough because it removes critical interactions between units of code, a dynamic language is even worse because changes to the real implementation interface (without modifications to the stub) can result in runtime type errors in production. Choosing to forgo the type check means that you might as well be writing JavaScript.

Can I use this with plain JavaScript?

It is really important that this library is used with TypeScript. It's a trick to use a Proxy object in place of the real implementation when calling createFacade, so nothing stops you from calling a function that does not exist. Especially bad would be destructuring so your fake hook could be used elsewhere in the program.

// hooks.js

export const { useSomethingThatDoesNotExist } = hooks;
// my-component.jsx

import { useSomethingThatDoesNotExist } from "./hooks";

const MyComponent = () => {
  const value = useSomethingThatDoesNotExist(); // throw new Error('oopsie-doodle!')
};

The only thing preventing you from cheating like this is good ol' TypeScript.

Is this safe to use?

Popular libraries like immer use the same trick of wrapping data T in a Proxy and present it as T, so I don't think you should be concerned. Proxy has ~95% browser support.