Filtering with React Server Components and URL Search Params

Filtering with React Server Components and URL Search Params

Traditionally, when you wanted to filter your data using React, you would first store the original data in local state, with the useState hook.

There would be a useEffect that watches for any filter changes, and then you would re-fetch the data using the applied filters on the client.

Once you get back the filtered data, you update the useState and the list re-renders, showing only the filtered results.

With the rise of React Server Components in Next.js 13, fetching data happens more and more on the server instead of the client. How can you add filters on the client, but still re-fetch and display the filtered data on the server? Using URL Search Parameters!

Key Takeaways:

00:00 - Intro into the project

00:56 - Current code setup, using Next.js App router and fetching initial data on the server

02:20 - Traditional filtering using useState and client side data fetching

03:14 - Server Actions allow for the filters to be inside a form element, with the action property

04:01 - Seeing the checkbox filters showing up inside of the server action's function

04:33 - Using search query parameters, we can re-fetch our filtered data on the server

05:49 - Constructing the URL search parameters with server actions

09:00 - We have access to the search parameters from our page.tsx server component

11:00 - Use the search params to filter our data on the initial server page load

11:52 - Demo of the search params working with React server components

12:37 - Make our checkboxes aware of the URL search params, and have them checked by default if the value is in the url

Did you find this article valuable?

Support Hunter Chang by becoming a sponsor. Any amount is appreciated!