A Guide to Integrating Formik and Redux for React Applications

David Pierre
June 30, 2020

If you're a React developer, you've likely faced challenges when dealing with complex forms. Managing forms in React can be a bit of a headache, especially when it involves handling input values, validation, error messages, and form submission. Fortunately, there are libraries available to simplify this process, such as Redux-Form and Formik. In this particular project, we opted to work with Formik due to its simplicity, self-sufficiency, and efficiency.

However, our project also relies on Redux for state management. This approach allows each component to access the necessary state from the store, ensuring consistent behavior throughout the entire application. While this combination of Formik and Redux offers several benefits, it raises a legitimate concern: how can we seamlessly integrate Formik with Redux to simplify form management?

In this blog post, I'll provide you with the answers you need. Keep reading to discover how to effectively integrate Formik with Redux, making form management in your React project a straightforward and efficient task.

Simplifying Form Management with Formik and Redux

Dealing with forms in React can be challenging, but it doesn't have to be. By integrating Formik and Redux, you can streamline the process and maintain clean, organized code. In this post, we'll walk through the integration steps and explore the benefits it brings.

Example with Formik

Let's start with a basic example from the Formik documentation to understand how it works:

 
// Basic Formik form example using render props.
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';

const BasicForm = () => (
   {
      const errors = {};
      // Validation logic here
      return errors;
    }}
    onSubmit={(values, { setSubmitting }) => {
      // Submission logic here
    }}
  >
    {({ isSubmitting }) => (
      
{/* Form fields here */}
)}
); export default BasicForm;

Formik provides components like [.code-inline]<Formik>[.code-inline], [.code-inline]<Form>[.code-inline], [.code-inline]<Field>[.code-inline], and [.code-inline]<ErrorMessage>[.code-inline] to simplify form management. In this example, we'll focus on the [.code-inline]handleSubmit[.code-inline] prop to integrate Redux.

How to Integrate Formik with Redux

To integrate Formik with Redux, follow these steps:

Set 1: API Request

 
export default class User {
  static signIn({ email, password }) {
    return api("/auth/login", {
      json: true,
      headers: {
        /* Here you handle the header of your request */
      },
    }).then((res) => res.body);
  }
}

Step 2: Redux Actions

Define your Redux actions and action creators:

 
export function loginSucceeded(user) {
  // Action logic here
}

export function requestLogin(user) {
  // Action logic here
}

export function loginFailed(user) {
  // Action logic here
}

Step 3: Action Creator

Create a function that wraps it altogether:

 
export const logInUser = (user) => {
  return (dispatch) => {
    dispatch(requestLogin(user));
    return signIn(user)
      .then((res) => {
        dispatch(loginSucceeded(res));
        return res;
      })
      .catch((err) => {
        dispatch(loginFailed(user));
      });
  };
}

Step 4: Integration

Now, integrate Redux into your form:

 
import React from 'react';
import { useDispatch } from 'react-redux';
import { useFormik } from 'formik';
import { logInUser } from './yourActionFile'; // Import your action creator here

const BasicForm = () => {
  const dispatch = useDispatch();

  const formik = useFormik({
    initialValues: {
      email: '',
      password: '',
    },
    validate: values => {
      const errors = {};
      // Validation logic here
      return errors;
    },
    onSubmit: (values, { setSubmitting }) => {
      const payload = {
        email: values.email,
        password: values.password,
      };
      dispatch(logInUser(payload)).finally(() => {
        setSubmitting(false);
      });
    },
  });

  return (
    
{/* Form fields here */}
); }; export default BasicForm;

Let's elaborate on the steps we've followed for integrating Formik with Redux:

  1. In the first step, we established a fundamental structure for making authentication requests to our API. This involves creating a class or module, such as the [.code-inline]User[.code-inline] class, that contains methods for interacting with the API.
  2. Next, we developed Redux actions and their corresponding action creators. These actions are designed to handle the data we retrieve from the API and manage it within the Redux store. In our example, we have actions like [.code-inline]loginSucceeded[.code-inline], [.code-inline]requestLogin[.code-inline], and [.code-inline]loginFailed[.code-inline] that indicate different states of the authentication process.
  3. In the third step, we encapsulated the entire authentication process within a single function, known as an action creator. This function, named [.code-inline]logInUse[.code-inline]r in our example, simplifies the process of initiating API requests, handling responses, and dispatching the appropriate Redux actions. By consolidating these operations, we ensure that wherever we need to trigger this authentication process in our application, it remains straightforward and consistent.
  4. In the final step, in the onSubmit method, we mapped our [.code-inline]logInUser[.code-inline] action creator to the [.code-inline] useDispatch[.code-inline] hook. This mapping allows us to access and utilize the action creator within our React component. Additionally, we implemented the [.code-inline]handleSubmit[.code-inline] function from Formik to manage form submissions effectively. We also can integrate some of Formik's built-in methods, like [.code-inline]setFieldValue[.code-inline], which plays a crucial role in handling form inputs, including triggering input value validation.

By following these steps, we've successfully integrated Formik with Redux, creating a cohesive and maintainable approach to form management. This integration simplifies complex forms while improving organization and maintainability, even for simpler forms.

Conclusion

Integrating Formik with Redux simplifies form management by decoupling logic from the form component itself. This approach is particularly beneficial for handling complex forms, but it also improves maintainability and organization in simpler forms.

What's your preferred method for managing forms in React? Do you have any unique approaches to combining Formik and Redux? If you think I missed any essential points, feel free to reach out or leave a comment. Your thoughts are valuable!