Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upstream PR #1

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/app"
}
]
}
46 changes: 35 additions & 11 deletions app/next.config.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
//
// Use Next Loaders on Linked Packages
// https://github.com/vercel/next.js/pull/13542#issuecomment-679085557
//
const path = require('path');

module.exports = {
webpack: (config) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
if (process.env.FORMIK_REDUCER_REFS) {
config.resolve.alias['formik'] = '@formik/reducer-refs';
}

// Important: return the modified config
return config;
},
}
webpack: (config, { defaultLoaders, webpack }) => {
config.module.rules = [
...config.module.rules,
{
test: /\.(tsx|ts|js|mjs|jsx)$/,
include: [path.resolve(config.context, '../')],
use: defaultLoaders.babel,
exclude: excludePath => {
return /node_modules/.test(excludePath);
},
},
];

// tsdx uses __DEV__
config.plugins.push(new webpack.DefinePlugin({
__DEV__: process.env.NODE_ENV === "development"
}));

// there can only be one
config.resolve.alias['react'] = path.resolve(config.context, '../node_modules/react');

return config;
},

onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60,
},
};
7 changes: 6 additions & 1 deletion app/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ function Home() {
</li>
<li>
<Link href="/perf500">
<a>Perf 500 (no styles!)</a>
<a>Performance Test: 500 Inputs (reducer-refs)</a>
</Link>
</li>
<li>
<Link href="/perf500v3">
<a>Performance Test: 500 Inputs (v3)</a>
</Link>
</li>
</ul>
Expand Down
61 changes: 61 additions & 0 deletions app/pages/perf500.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React from "react";
import { Formik, Form, useField, FieldHookConfig } from "@formik/reducer-refs";

const Input = (p: FieldHookConfig<string>) => {
const [field, meta] = useField(p);
const renders = React.useRef(0);
return (
<>
<label>{p.name} </label>
<input {...field} />
<div>{renders.current++}</div>
{meta.touched && meta.error ? (
<div>{meta.error.toString()}</div>
) : null}
<small>
<pre>{JSON.stringify(meta, null, 2)}</pre>
</small>
</>
);
};

const isRequired = (v) => {
return v && v.trim() !== "" ? undefined : "Required";
};

const array = new Array(500).fill(undefined);

const initialValues = array.reduce((prev, curr, idx) => {
prev[`Input ${idx}`] = "";
return prev;
}, {});

const onSubmit = async (values: typeof initialValues) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
};

const kids = array.map((_, i) => (
<Input key={`input-${i}`} name={`Input ${i}`} validate={isRequired} />
));

export default function App() {
return (
<div>
<div>
<h1>Formik v3 with 500 controlled fields</h1>
<div>
<span>#</span> = number of renders
</div>
</div>
<Formik onSubmit={onSubmit} initialValues={initialValues}>
<Form>
{kids}
<button type="submit" >
Submit
</button>
</Form>
</Formik>
</div>
);
}
12 changes: 6 additions & 6 deletions app/pages/perf500.js → app/pages/perf500v3.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from "react";
import { Formik, Form, useField } from "formik";
import { Formik, Form, useField, FieldHookConfig } from "formik";

const Input = (p) => {
const Input = (p: FieldHookConfig<string>) => {
const [field, meta] = useField(p);
const renders = React.useRef(0);
return (
Expand All @@ -10,7 +10,7 @@ const Input = (p) => {
<input {...field} />
<div>{renders.current++}</div>
{meta.touched && meta.error ? (
<div>{meta.error}</div>
<div>{meta.error.toString()}</div>
) : null}
<small>
<pre>{JSON.stringify(meta, null, 2)}</pre>
Expand All @@ -23,14 +23,14 @@ const isRequired = (v) => {
return v && v.trim() !== "" ? undefined : "Required";
};

const array = new Array(500).fill();
const array = new Array(500).fill(undefined);

const initialValues = array.reduce((prev, curr, idx) => {
prev[`Input ${idx}`] = "";
return prev;
}, {});

const onSubmit = async (values) => {
const onSubmit = async (values: typeof initialValues) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
};
Expand All @@ -49,7 +49,7 @@ export default function App() {
</div>
</div>
<Formik onSubmit={onSubmit} initialValues={initialValues}>
<Form >
<Form>
{kids}
<button type="submit" >
Submit
Expand Down
23 changes: 19 additions & 4 deletions app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,29 @@
"noEmit": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true
"isolatedModules": true,
"baseUrl": "../",
"paths": {
"formik": [
"packages/formik/src"
],
"formik-native": [
"packages/formik-native/src"
],
"@formik/core": [
"packages/@formik/core/src"
],
"@formik/reducer-refs": [
"packages/@formik/reducer-refs/src"
]
}
},
"exclude": [
"node_modules"
],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@
"cypress": "cypress run",
"precommit": "lint-staged",
"cypress:open": "cypress open",
"start:app": "npm run build && yarn --cwd packages/formik link && yarn --cwd node_modules/react link && yarn --cwd ./app link react formik && yarn --cwd ./app && yarn --cwd ./app run dev",
"start:reducer-refs": "npm run build && yarn --cwd packages/formik-core link && yarn --cwd packages/formik-reducer-refs link @formik/core && yarn --cwd packages/formik-reducer-refs link && yarn --cwd node_modules/react link && yarn --cwd ./app link react @formik/core @formik/reducer-refs && cross-env FORMIK_REDUCER_REFS=1 yarn --cwd ./app && cross-env FORMIK_REDUCER_REFS=1 yarn --cwd ./app run dev",
"start": "yarn --cwd ./app && yarn --cwd ./app run dev",
"unlink": "yarn --cwd node_modules/react unlink && yarn --cwd packages/formik unlink"
},
"lint-staged": {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@ import {
FormikConfig,
FieldRegistry,
FormikMessage,
FieldMetaProps,
FieldHelperProps,
FieldInputProps,
FormikCoreApi,
} from './types';
import { useEventCallback, isFunction, isObject, getIn } from './utils';
} from '../types';
import { useEventCallback, isFunction, isObject, getIn } from '../utils';
import {
selectRunValidateHandler,
selectRunValidationSchema,
Expand All @@ -35,7 +34,8 @@ import {
selectExecuteChange,
selectHandleChange,
selectHandleBlur,
} from './selectors';
selectGetFieldMeta,
} from '../selectors';
import React from 'react';

export const useFormikCore = <Values extends FormikValues>(
Expand Down Expand Up @@ -251,19 +251,8 @@ export const useFormikCore = <Values extends FormikValues>(
* They use refs!
*/
const getFieldMeta = React.useCallback(
(name: string): FieldMetaProps<any> => {
const state = getState();

return {
value: getIn(state.values, name),
error: getIn(state.errors, name),
touched: !!getIn(state.touched, name),
initialValue: getIn(state.initialValues, name),
initialTouched: !!getIn(state.initialTouched, name),
initialError: getIn(state.initialErrors, name),
};
},
[]
selectGetFieldMeta(getState),
[getState]
);

const getFieldHelpers = React.useCallback(
Expand Down
24 changes: 24 additions & 0 deletions packages/@formik/core/src/hooks/usePropChangeLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useRef, useEffect } from 'react';

/**
* https://stackoverflow.com/a/51082563/1639736
*/
export function usePropChangeLogger<Shape extends object>(props: Shape) {
const prev = useRef<Record<string, any>>(props);

useEffect(() => {
const changedProps = Object.entries(props)
.reduce<Record<string, [any, any]>>((ps, [k, v]) => {
if (prev.current[k] !== v) {
ps[k] = [prev.current[k], v];
}
return ps;
}, {});

if (Object.keys(changedProps).length > 0) {
console.log('Changed props:', changedProps);
}

prev.current = props;
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ export * from './constants';
export * from './reducer';
export * from './selectors';
export * from './types';
export * from './useFormikCore';
export * from './hooks/useFormikCore';
export * from './utils';
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
FieldInputProps,
SetFieldTouched,
ValidateFormFn,
FieldMetaProps,
} from './types';
import { isFunction, isEqual } from 'lodash';
import deepmerge from 'deepmerge';
Expand Down Expand Up @@ -670,3 +671,17 @@ export const selectGetFieldProps = <Values extends FormikValues>(
}
return field;
};
export const selectGetFieldMeta = <Values extends FormikValues>(
getState: GetStateFn<Values>
) => (name: string): FieldMetaProps<any> => {
const state = getState();

return {
value: getIn(state.values, name),
error: getIn(state.errors, name),
touched: !!getIn(state.touched, name),
initialValue: getIn(state.initialValues, name),
initialTouched: !!getIn(state.initialTouched, name),
initialError: getIn(state.initialErrors, name),
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export interface FormikHandlers {
getFieldMeta: <Value>(name: string) => FieldMetaProps<Value>;
getFieldHelpers: GetFieldHelpersFn;
}
export type FormikCoreApi<Values extends FormikValues> =
export type FormikCoreApi<Values extends FormikValues> =
Omit<FormikHelpers<Values>, 'validateForm'> & FormikHandlers & {
validateFormWithLowPriority: ValidateFormFn<Values>,
validateFormWithHighPriority: ValidateFormFn<Values>,
Expand Down Expand Up @@ -252,7 +252,7 @@ export interface FormikConfig<Values> extends FormikSharedConfig {
validate?: (values: Values) => void | object | ValidateFormFn<Values>;

/** Inner ref */
innerRef?: React.Ref<FormikProps<Values>>;
innerRef?: React.Ref<FormikCoreApi<Values>>;
}

/**
Expand Down
Loading