Formik & Persisting state

I have moved from using redux-form to using formik. Forms are in its essence ephemeral and you should not need (EVER) to save its state anywhere else but the Form’s state (or some HOC controlling the state).

But every now and then you come across an issue, where you would actually like to save the form’s state and then have it reinstate later. redux-form has prop called destroyOnMount which controls whether or not you want to keep the form’s state in redux after the form unmounts. formik -out of the box- does not come with any solution for this - and for a good reason!

But let me give you an use case:
1. user enters screen with form
2. user enters some values into the form
3. user sees a link contained in the form (e.g. terms & conditions)
4. user clicks the link and is taken somewhere else in the app to read the terms & conditions
5. user clicks the back button to go back to the form
6. the entered values are gone

How to persist

I’ve created this little component — FormikPersist, that takes advantage of formik’s FormikConsumer (see React Context for more info). On every key stroke it saves the form’s state into the sessionStorage. It pulls the state from the sessionStorage when mounted. And clears the sessionStorage when you refresh or close the tab.

The gist of saving / restoring the state is in the componentDidMount / componentDidUpdate methods, which can be modified to best fit your application, even to save the form’s state to the redux. But you don’t want to do that, believe me.

How to use it

You basically just place the <FormikPersist /> component inside the <Formik> component and pass it a name — because formik’s forms do not have id / name property and you need to distinguish between different persisted data.

You may wish to turn the persistence on / off, you can do so by passing a prop to your component to control this, as such:

Hope this helps someone save an hour or two.