diff --git a/README.md b/README.md index cae5e49..65fa6f2 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_828 TILs and counting..._ +_829 TILs and counting..._ --- @@ -567,6 +567,7 @@ _828 TILs and counting..._ - [Spelunking Through Components With Enzyme's Dive](react/spelunking-through-components-with-enzymes-dive.md) - [Sync Your react-router State With Redux](react/sync-your-react-router-state-with-redux.md) - [Test Files In create-react-app](react/test-files-in-create-react-app.md) +- [Update Formik Initial Values When Props Change](react/update-formik-initial-values-when-props-change.md) - [Upgrading To The Latest React In CodeSandbox](react/upgrading-to-the-latest-react-in-codesandbox.md) - [Use A Ref To Autofocus An Input](react/use-a-ref-to-autofocus-an-input.md) - [Use React 16 With Gatsby](react/use-react-16-with-gatsby.md) diff --git a/react/update-formik-initial-values-when-props-change.md b/react/update-formik-initial-values-when-props-change.md new file mode 100644 index 0000000..dc08c33 --- /dev/null +++ b/react/update-formik-initial-values-when-props-change.md @@ -0,0 +1,44 @@ +# Update Formik Initial Values When Props Change + +When a [Formik](https://jaredpalmer.com/formik/) form mounts, whatever the +initial values are set to is what they will be. Even if the initial values are +computed from props, those props changing will not affect `initialValues` after +mount. + +```javascript +const ZipForm = ({ currentZip }) => { + return ( + { + // do stuff + }} + ... +``` + +If we are fetching the user's saved zip code asynchronously from a server while +the form is first being rendered, then `currentZip` will start as an empty +value. Once the async request comes back and `currentZip` is set, we won't see +the form update the `zip` field. + +There was a time when you would have to jump through some hoops to make sure +the freshest prop value made it into the form. Now, Formik provides a handier +mechanism -- the `enableReinitialize` prop. + +```javascript +const ZipForm = ({ currentZip }) => { + return ( + { + // do stuff + }} + ... +``` + +By setting `enableReinitialize` to true, we are telling Formik that any prop +changes that flow into the `initialValues` object should cause those values to +be _reinitialized_. + +See a [live example](https://codesandbox.io/s/sad-mendeleev-4dbbp).