DEV Community

Cover image for Choosing the Best Approach: React Router vs. Conditional Rendering for Multi-Step Forms
Hamdan Khan
Hamdan Khan

Posted on

Choosing the Best Approach: React Router vs. Conditional Rendering for Multi-Step Forms

Have you ever come across the decision of whether to choose React Router or Conditional rendering when creating a Multi-step form or a component that involves multiple steps? Let's discuss which one is the best approach and why.

Whether it is a survey form, a dashboard, or a checkout process, developers often can't figure out the best approach to create the components. Keeping the performance of the site in mind, they need to carefully consider whether to leverage React Router or utilize conditional rendering. Both approaches have their strengths and considerations that can impact the overall performance of the site.

Overview of React Router and Conditional Rendering:

Generally speaking, React Router and Conditional rendering both have their different and unique use cases and commonly we do not get to see a conflict of choice between these two. But in the case of multi-step forms, developers often find themselves at a crossroads.

React Router:

React Router, a powerful routing library for React applications, provides a structured way to handle navigation and rendering of different components based on URLs. By defining routes and associating them with specific components, React Router ensures a smooth user experience as users navigate through different steps or pages of the form. It efficiently manages the state and re-renders only the necessary components, optimizing performance by reducing unnecessary component updates.

Conditional Rendering:

Conditional rendering offers a dynamic approach. Developers can conditionally render components based on specific conditions or states within the application. This approach can be advantageous for performance since it allows for more fine-grained control over rendering, avoiding unnecessary re-renders of components that are not currently needed. However, improper use of conditional rendering can lead to complex logic and potentially impact performance if not carefully implemented.

Demonstration using React Router:

A demonstration of a simple multi-step form using React-router looks can be seen below. You can also implement lazy loading for a better experience according to your needs.
In this code, different step components named Step1, Step2, and so on are defined as routes with their paths accordingly.

// App.js

import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Step1 from './components/Step1';
import Step2 from './components/Step2';
import Step3 from './components/Step3';
import Summary from './components/Summary';

function App() {
  return (
    <Router>
      <div className="App">
        <Routes>
          <Route exact path="/" component={Step1} />
          <Route path="/step2" component={Step2} />
          <Route path="/step3" component={Step3} />
          <Route path="/summary" component={Summary} />
        </Routes>
      </div>
    </Router>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

The Step components are likely defined as follows, which redirect to the next component by the redirect utility from react-router.

// Step1.js

import React from 'react';
import { redirect } from 'react-router-dom';

function Step1() {

  const handleNext = () => {
    // Navigates to the given location
    redirect("/step2");
  };

  return (
    <div>
      <h2>Step 1</h2>
      {/* Add your form fields and logic here */}
      <button onClick={handleNext}>Next</button>
    </div>
  );
}

export default Step1;
Enter fullscreen mode Exit fullscreen mode

In the same way, the other steps' components can be defined.

Demonstration using Conditional rendering:

Multi-step form created using conditional rendering is demonstrated as follows, in which a state "step" which keeps track of the form steps is created. With the help of switch-cases or logical operator AND (&&), the components corresponding to the state can be rendered.

import React, { useState } from "react";
import Step1 from './components/Step1';
import Step2 from './components/Step2';
import Step3 from './components/Step3';

const MultiStepForm = () => {
  const [step, setStep] = useState(1);

  const renderStep = () => {
    switch (step) {
      case 1:
        return (
          <Step1 setStep={setStep}/>
        );
      case 2:
        return (
          <Step2 setStep={setStep}/>
        );
      case 3:
        return (
          <Step3 setStep={setStep}/>
        );
      default:
        return null;
    }
  };


  return <div>{renderStep()}</div>;
};

export default MultiStepForm;

Enter fullscreen mode Exit fullscreen mode

The steps components follow a similar logic as in the previous method but instead of navigating to the given location by clicking the Next or Previous button, the state "step" is updated which renders the matching step as in switch case statements.

// Step1.js

import React from 'react';
import { redirect } from 'react-router-dom';

function Step1({setStep}) {

  const handleNext = () => {
    // Updates the "step" state
    setStep(2);
  };

  return (
    <div>
      <h2>Step 1</h2>
      {/* Add your form fields and logic here */}
      <button onClick={handleNext}>Next</button>
    </div>
  );
}

export default Step1;
Enter fullscreen mode Exit fullscreen mode

Similarly, the other steps' components can be made using the same logic.

Comparison between the both:

1) React Router:

  • React Router optimizes performance by loading components only when necessary.

  • React Router leverages browser history and URL management, enabling smooth navigation and efficient URL handling.

  • Structured for code splitting and lazy loading components on-demand, reducing initial load times.

  • Offers a high level of flexibility as it provides a structured approach to handle routing, making it easier to add new steps or modify the form flow.

  • Provides an organized and structured codebase, facilitating collaboration and future updates.

2) Conditional Rendering:

  • Conditional rendering provides control over rendering components by rendering only the necessary components.

  • URL management can not be achieved efficiently when using Conditional rendering.

  • Code splitting and Lazy loading can also be achieved in this method but can lead to complex code as steps increase.

  • Also offers flexibility on small-scale projects, however managing complex conditional logic across multiple steps can become challenging.

  • Can sometimes lead to complex and nested code structures. As the number of steps increases, the conditional logic may become complicated.

Conclusion:

In conclusion, React Router and conditional rendering each offer distinct advantages for creating multi-step forms. React Router excels in performance optimization, flexibility, and code organization, while conditional rendering provides fine-grained control and customization.

  • Conditional rendering can be a better choice for small-scale projects as it provides more control (such as Registration pages, review forms, and filtered searches).

  • While React router is a good fit for complex projects as it provides a structured way of writing code (such as Survey forms, dashboards, complex data entry forms, and checkout processes).

Top comments (0)