DEV Community

Cover image for Building a Searchable Product List with React Server Components
HexShift
HexShift

Posted on

Building a Searchable Product List with React Server Components

React Server Components (RSC) are a powerful tool for building dynamic, full-stack applications that offer high performance while reducing the amount of client-side code. In this tutorial, we'll build a searchable product list that leverages server-side rendering to display filtered products, improving both performance and user experience.


Step 1 - Setting Up the Project

Start by setting up a new React project with Express for server-side rendering. This will allow us to serve the filtered product list from the server side.

npx create-react-app product-search
cd product-search
npm install express react-server-dom
Enter fullscreen mode Exit fullscreen mode

Create the Express server by adding a server.js file:

// server.js
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./src/App');

const app = express();

app.get('/', (req, res) => {
  const appString = ReactDOMServer.renderToString();
  res.send(`


      Product Search

        ${appString}



  `);
});

app.listen(3000, () => console.log('Server is running on http://localhost:3000'));
Enter fullscreen mode Exit fullscreen mode

Step 2 - Creating the Searchable Product List

Next, create a component that will render the product list. For now, let’s make it static:

// ProductList.js
import React from 'react';

const products = [
  { id: 1, name: 'Product 1', price: '$10' },
  { id: 2, name: 'Product 2', price: '$20' },
  { id: 3, name: 'Product 3', price: '$30' },
];

const ProductList = () => {
  return (

      <h2>Product List</h2>
      <ul>
        {products.map(product =&gt; (
          <li>
            {product.name} - {product.price}
          </li>
        ))}
      </ul>

  );
};

export default ProductList;
Enter fullscreen mode Exit fullscreen mode

Step 3 - Implementing Server-Side Search Filtering

Instead of fetching products on the client-side, we will filter them server-side based on the query string in the URL. Let’s modify our ProductList component to handle this:

// ProductList.js
import React, { useEffect, useState } from 'react';

const ProductList = ({ query }) =&gt; {
  const [products, setProducts] = useState([]);

  useEffect(() =&gt; {
    const fetchProducts = async () =&gt; {
      const response = await fetch(`/api/products?search=${query}`);
      const data = await response.json();
      setProducts(data);
    };

    fetchProducts();
  }, [query]);

  if (!products.length) return <p>No products found.</p>;

  return (

      <h2>Product List</h2>
      <ul>
        {products.map(product =&gt; (
          <li>
            {product.name} - {product.price}
          </li>
        ))}
      </ul>

  );
};

export default ProductList;
Enter fullscreen mode Exit fullscreen mode

Step 4 - Setting Up the Server to Handle the Search Request

In server.js, we need to handle the search query and filter products on the server side. We’ll assume the product data is stored in an array for simplicity.

// server.js
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./src/App');

const app = express();

// Simulated product data
const products = [
  { id: 1, name: 'Product 1', price: '$10' },
  { id: 2, name: 'Product 2', price: '$20' },
  { id: 3, name: 'Product 3', price: '$30' },
];

app.get('/api/products', (req, res) =&gt; {
  const searchQuery = req.query.search || '';
  const filteredProducts = products.filter(product =&gt;
    product.name.toLowerCase().includes(searchQuery.toLowerCase())
  );
  res.json(filteredProducts);
});

app.get('/', (req, res) =&gt; {
  const appString = ReactDOMServer.renderToString();
  res.send(`


      Product Search

        ${appString}



  `);
});

app.listen(3000, () =&gt; console.log('Server is running on http://localhost:3000'));
Enter fullscreen mode Exit fullscreen mode

Step 5 - Adding the Search Input

To allow users to filter the product list, we need a search input. We can implement this input in the App.js component:

// App.js
import React, { useState } from 'react';
import ProductList from './ProductList';

const App = () =&gt; {
  const [searchQuery, setSearchQuery] = useState('');

  const handleSearchChange = (event) =&gt; {
    setSearchQuery(event.target.value);
  };

  return (

      <h1>Product Search</h1>



  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Use Case Scenario

In a typical e-commerce application, users often want to filter through a large catalog of products to find the ones that meet their specific needs. By leveraging React Server Components to render the product list and filter it server-side, we ensure faster load times and a seamless experience. This approach is particularly useful for search-heavy applications, where server-side filtering can reduce client-side processing and improve responsiveness.


✅ Pros and ❌ Cons

✅ Pros:

  • ⚡ Faster load times and improved performance by leveraging server-side rendering.
  • 💻 Minimal client-side processing, reducing the amount of JavaScript that needs to be executed on the browser.
  • 🧑‍💻 Simplified data fetching, as React Server Components handle the server-side logic.

❌ Cons:

  • 🔄 Increased complexity in managing server-side routes and data fetching.
  • 🧩 More intricate setup for routing and state management in full-stack applications.
  • ⚙️ Requires good knowledge of both React and server-side rendering to implement effectively.

Summary

In this article, we’ve built a searchable product list using React Server Components and server-side filtering. By using server-side rendering, we ensure that users get the results they need quickly while maintaining an optimal user experience. If you want to dive deeper into React Server Components and build even more sophisticated applications, check out my full guide:

Mastering React Server Components: A Pro Guide to Modern Full-Stack React – just $5.


If this was helpful, you can also support me here: Buy Me a Coffee

Top comments (0)