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 🙏

© 2025 – Pkg Stats / Ryan Hefner

forming

v0.0.22

Published

Build form with least re-renders!

Readme

forming

Build form with least re-renders!

NPM JavaScript Style Guide

Install

npm install --save forming

Forming exposes two basic components, Form and Field. Field accepts a functional component as children to achieve minimum performance gain where it doesn't need to udpate other fields when its value is updated.

Usage

import { Form, Field } from 'forming';

export function Example() {
  return (
    <div className="flex flex-col items-start">
      <h2 className="text-2xl">async validating</h2>
      <Form
        initialValues={{
          email: '[email protected]',
        }}
        validateOnSubmit
        onSubmit={({ values }) => {
          console.log('submitting', values);
        }}
      >
        <Field
          name="email"
          validate={{
            required: 'Email is required',
          }}
          validateOnChange
        >
          {({ value = '', onChange, errors }) => {
            return (
              <div className="flex flex-col items-start">
                <label htmlFor="">
                  Email (Required, also validate onChange)
                </label>
                <input
                  value={value}
                  onChange={onChange}
                  className="border border-black border-solid"
                />
                {errors && errors.length > 0 && (
                  <div className="text-red-500">{errors[0].message}</div>
                )}
              </div>
            );
          }}
        </Field>
        <Field
          validateDebouncedTime={300}
          name="username"
          validate={{
            minLen: (val: string) => {
              if (val.length < 2) {
                return 'Minimum length is 2';
              }

              return ''; // or return true
            },
            valid: async (val: string) => {
              const result = await checkUsername(val);
              if (result === 'valid') {
                return '';
              }
              return 'invalid';
            },
          }}
          validateOnChange
        >
          {({ value = '', updateValue, errors, isValidating }) => {
            return (
              <div className="flex flex-col items-start">
                <label htmlFor="">Username</label>
                <input
                  value={value}
                  onChange={e => {
                    // don't have to use preset "onChange" for flexible update
                    updateValue(e.target.value);
                  }}
                  className="border border-black border-solid"
                />
                {errors && errors.length > 0 && (
                  <div className="text-red-500">{errors[0].message}</div>
                )}
                {isValidating && <div>is validating</div>}
              </div>
            );
          }}
        </Field>
        <SubmitBtn />
      </Form>
    </div>
  );
}

Recipes

Validate field on change

You can validate the field in either sync or async manner.

<Field
  validateDebouncedTime={300}
  name="username"
  validate={{
    // sync
    minLen: (val: string) => {
      if (val.length < 2) {
        return 'Minimum length is 2';
      }

      return ''; // or return true
    },
    // async
    valid: async (val: string) => {
      const result = await checkUsername(val);
      if (result === 'valid') {
        return '';
      }
      return 'invalid';
    },
  }}
  validateOnChange
>
  {({ value = '', updateValue, errors, isValidating }) => {
    return (
      <div className="flex flex-col items-start">
        <label htmlFor="">Username</label>
        <input
          value={value}
          onChange={e => {
            updateValue(e.target.value);
          }}
          className="border border-black border-solid"
        />
        {errors && errors.length > 0 && (
          <div className="text-red-500">{errors[0].message}</div>
        )}
        {isValidating && <div>is validating</div>}
      </div>
    );
  }}
</Field>

Access other fields state (value, errors, changed)

There are several hooks you can use

  • useFormValue

This is used to read a single other field value from current field component. It's a singular use case of useFormValues

const FullNameField = () => {
  const firstName = useFormValue('firstName');
  const lastName = useFormValue('lastName');
  const fullName = `${firstName} ${lastName}`;
  return <div>{fullName}</div>;
};
  • useFormValues This is useful to get multiple field values or all field values
const FullNameField = () => {
  const { firstName, lastName } = useFormValues(['firstName', 'lastName']); // only re-render when these two fields change value
  // or
  const { firstName, lastName } = useFormValues(); // will re-render when other fields change value even though we only use firstName and lastName.
};
  • useFormError

This is a singular use case of useFormErrors, in most case, you may want to use useFormErrors for convenience

const SubmitBtn = () => {
  const errors = useFormError('password');
  return (
    <button type="submit" disabled={errors && errors.length > 0}>
      Submit
    </button>
  );
};
  • useFormErrors Enhanced version of useFormError, where you can pass an array of names to get their errors. If you don't pass in any names, then it will subscribe to the errors of all fields
const SubmitBtn = () => {
  const errors = useFormErrors(['username', 'password']);
  const allFieldsErrors = useFormErrors();
  return (
    <button type="submit" disabled={errors && errors.length > 0}>
      Submit
    </button>
  );
};
  • useFormChanged This is useful to test if the form values are still pristine, it will be triggered once field values changed. Note: this only detects if user has changed the value, but doesn't guarantee the final value is the different than initial value. e.g. user firstly change username value from 'foo' to 'foob', and then change back to 'foo'. This field is still considered changed.
const SubmitBtn = () => {
  const otherFieldChanged = useFormChanged('otherField');
  const allFieldChanged = useFormChanged();
};

Control form state outside form

There are scenarios where we need to access or update form state outside of Form Component. use innerRef on the Form Component.

export function Example6() {
  const formRef = useRef<FormRefProps<any>>(null);
  return (
    <div className="flex flex-col items-start">
      <h2 className="text-2xl">use outside of form</h2>
      <Form innerRef={formRef}>
        <Field
          name="feedback"
          validate={{
            minLen: val => {
              if (val.length < 3) {
                return 'minimum length is 3';
              }
              return '';
            },
          }}
        >
          {({ value = '', onChange, errors }) => {
            return (
              <div className="flex flex-col items-start">
                <label htmlFor="">Leave a feedback</label>
                <input
                  value={value}
                  onChange={onChange}
                  className="border border-black border-solid"
                />
                {errors && errors.length > 0 && (
                  <div className="text-red-500">{errors[0].message}</div>
                )}
              </div>
            );
          }}
        </Field>
        <div className="flex justify-between">
          <button
            type="button"
            className="bg-green-500"
            onClick={() => {
              if (formRef.current) {
                formRef.current.validate('feedback');
                console.log(formRef.current.getValues());
              }
            }}
          >
            Accept
          </button>
          <button
            type="button"
            className="bg-red-500"
            onClick={() => {
              if (formRef.current) {
                formRef.current.validate('feedback');
                console.log(formRef.current.getValues());
              }
            }}
          >
            Reject
          </button>
        </div>
      </Form>
    </div>
  );
}

License

MIT © liqiang372