Bad ways you’re using react – Separating JSX

Share This Post

Writing scalable react apps is an art in its own way. As your apps scale they become bigger, more complex; more components are added, and more business logic and requirements need to be integrated into your project.

A common mistake I see beginners face as their projects scale, is they tend to write all of their code inside enormous files. Components with mixed business logic and JSX are created, and before you know it, you have to keep scrolling up and down on a 700 line file to keep track of the project.

This blog explains why seperating your JS from your JSX can help avoid this issue, through refactoring and moving your logical functions written in JavaScript, your project can be constructed of small re-usable components that utilize JS functions to implement their functionality.

Why ChatGPT says you should care

Separating your JavaScript code from your React code can provide several benefits:

  • Organization and maintainability: Separating your JavaScript code from your React code can make it easier to organize and maintain your codebase. By keeping your JavaScript code separate, you can better manage dependencies, isolate functionality, and make it easier to update or replace specific parts of your application.
  • Scalability: As your application grows and becomes more complex, separating your JavaScript code from your React code can help you manage that complexity. By breaking your application down into smaller, more manageable pieces, you can avoid bloated files and keep your codebase more scalable.
  • Code reuse: Separating your JavaScript code from your React code can also make it easier to reuse functionality across different parts of your application or even across different applications. By breaking your code down into smaller, more modular pieces, you can create reusable components and modules that can be easily integrated into other parts of your codebase.
  • Performance: Separating your JavaScript code from your React code can also improve the performance of your application. By keeping your JavaScript code separate, you can take advantage of code splitting techniques that can help reduce the amount of JavaScript that needs to be loaded and parsed by the browser.

An Example

Let’s say you’re building a simple e-commerce website using React. You have a page that displays a list of products, and you want to implement a feature that allows users to filter the list by price range.

If you mix your JavaScript and React code together, you might end up with something like this:

const ProductList = ({ products }) => {
  const [minPrice, setMinPrice] = useState('');
  const [maxPrice, setMaxPrice] = useState('');

  const filteredProducts = products.filter((product) => {
    if (minPrice && maxPrice) {
      return product.price >= minPrice && product.price <= maxPrice;
    } else if (minPrice) {
      return product.price >= minPrice;
    } else if (maxPrice) {
      return product.price <= maxPrice;
    } else {
      return true;
    }
  });

  return (
    <div>
      <div>
        <label>Min Price:</label>
        <input type="number" value={minPrice} onChange={(e) => setMinPrice(e.target.value)} />
      </div>
      <div>
        <label>Max Price:</label>
        <input type="number" value={maxPrice} onChange={(e) => setMaxPrice(e.target.value)} />
      </div>
      <ul>
        {filteredProducts.map((product) => (
          <li key={product.id}>{product.name} - ${product.price}</li>
        ))}
      </ul>
    </div>
  );
}

While this code works, it’s not very modular or reusable. If you wanted to reuse the filtering functionality in another part of your application, you’d need to copy and paste this code or extract it into a separate function or module.

Instead, you can separate your JavaScript code from your React code by creating a separate filtering module. Here’s what that might look like:

  export const filteredProducts (products, minPrice, maxPrice) = products.filter((product) => {
    if (minPrice && maxPrice) {
      return product.price >= minPrice && product.price <= maxPrice;
    } else if (minPrice) {
      return product.price >= minPrice;
    } else if (maxPrice) {
      return product.price <= maxPrice;
    } else {
      return true;
    }
  });

  return filteredProducts;
}

You can then use this JavaScript function in any component that’s needed, keeping your components to using mostly JSX

const ProductList = ({ products }) => {
  const [minPrice, setMinPrice] = useState('');
  const [maxPrice, setMaxPrice] = useState('');

  const filteredProducts = useMemo(() => 
    filteredProducts(products, minPrice, maxPrice), 
  [minPrice, maxPrice, products])

  return (
    <div>
      <div>
        <label>Min Price:</label>
        <input type="number" value={minPrice} onChange={(e) => setMinPrice(e.target.value)} />
      </div>
      <div>
        <label>Max Price:</label>
        <input type="number" value={maxPrice} onChange={(e) => setMaxPrice(e.target.value)} />
      </div>
      <ul>
        {filteredProducts.map((product) => (
          <li key={product.id}>{product.name} - ${product.price}</li>
        ))}
      </ul>
    </div>
  );
}

Leave a Reply

Digital art dealers

Join our vibrant community of more than 750 members by subscribing to our newsletter. Every Monday, you'll receive a programming meme to kickstart your week.

follow us on

© 2023 Digital Art Dealers. All rights reserved.

%d bloggers like this: