Video thumbnail for ARRÊTE d'utiliser useState, met plutôt le state dans l'URL !

Stop Using useState! Manage React State with URL Parameters (Next.js)

Summary

Quick Abstract

Confused about keeping your application state in the URL? This summary breaks down the "state in URL" concept, highlighting how it enhances user experience & SEO! Learn how to implement this with Next.js, making your web app more shareable, bookmarkable, and user-friendly. Discover how to manage URL parameters, improve navigation, and leverage libraries like nux-47 for cleaner code.

Quick Takeaways:

  • Shareable State: Users can share your site with the exact UI and filters applied, improving collaboration.

  • Bookmarkable URLs: Users can save URLs to return to the same state later.

  • Navigation: Back/Forward buttons work seamlessly, allowing users to easily navigate through different states.

  • Refresh Resilience: Refreshing the page preserves the current state.

  • Direct URL Manipulation: Tech-savvy users can directly modify the URL for advanced interactions.

  • Next.js Implementation: Utilise libraries for clean code, avoiding boilerplate and improving maintainability.

Maintaining State in the URL for Web Applications

When developing web applications, it's crucial to manage the application's state within the URL. This practice offers numerous benefits for user experience and maintainability. Let's explore what it means to keep state in the URL and the advantages it provides.

What is Keeping State in the URL?

Keeping state in the URL involves reflecting the application's current state (e.g., filters, search terms, pagination) as parameters in the URL. For example, if you search for "shirt" on a website, the URL might update to include ?search=shirt. Similarly, selecting "blue" would modify the URL to ?search=shirt&color=blue. Each interaction that changes the UI should update the URL accordingly.

Advantages of Storing State in the URL

There are several key advantages to storing state information within the URL of your web application.

  • Shareable Links: Users can easily share the current state of the application with others. When a user shares a URL containing state parameters, the recipient will see the exact same UI and data. This simplifies collaboration and communication.

  • Bookmarking: Users can bookmark URLs to save specific states of the application. When the user returns to the bookmarked URL, the application will restore the saved state, providing a seamless experience.

  • Browser History Navigation: Users can use the browser's back and forward buttons to navigate through different application states. Each state change, reflected in the URL, becomes a point in the browser's history.

  • Page Refreshes: Refreshing the page preserves the current state. The application reads the parameters from the URL and reloads the UI with the corresponding data, preventing data loss.

  • Direct URL Manipulation: Advanced users can directly modify the URL to achieve specific states, useful for debugging or specialized tasks such as web scraping (though not necessarily the ideal approach for that).

Implementation Example using Next.js

The transcript dives into a detailed example of implementing this technique in a Next.js application. While the original approach involves using useEffect and manipulating window.history, a more efficient method leveraging Next.js's features and external libraries is demonstrated.

Initial Implementation (Less Clean)

The initial implementation uses useEffect to synchronize the component's state with the URL and vice-versa:

  1. Synchronizing state with the DOM: A useEffect hook listens for changes to window.location.search and updates the component's state accordingly. This ensures the component reflects the URL parameters.

  2. Updating the URL on state changes: Another useEffect hook listens for changes to the component's state. When the state changes, it constructs a new URL using URLSearchParams and updates the browser's history using window.history.pushState.

This approach, while functional, can be verbose and less maintainable.

Using Next.js Router

Next.js provides a router object that simplifies URL manipulation. Instead of directly using window.history.pushState, you can use router.push to update the URL. This approach also allows you to control scroll behavior.

router.push({
  pathname: '/',
  query: { color: newValue },
}, undefined, { scroll: false });

Using useSearchParams Hook

Next.js offers the useSearchParams hook, providing a cleaner way to access and modify URL parameters. This hook simplifies the code by eliminating the need for multiple useEffect hooks.

Using nux.47ng.com Library (Recommended)

For an even cleaner and more robust solution, the nux.47ng.com library is highly recommended. This library provides a useQueryState hook that simplifies managing query parameters:

const [color, setColor] = useQueryState('color');

The library also offers options for parsing and validation:

  • shallow: false: Ensures that the server is notified of changes to the query string, triggering a re-render of the server component.

  • parseAs: Provides for type-safe parsing of parameters.

Server-Side Validation

For production applications, server-side validation of URL parameters is crucial. nux.47ng.com offers a createSearchParamsCache function to achieve this. This function allows you to define schemas for your URL parameters and ensure that only valid values are processed. This server-side data validation prevents application crashes due to unexpected input.

Conclusion

Maintaining state in the URL is a valuable practice that enhances the user experience and simplifies web application development. While various approaches exist, leveraging Next.js's useSearchParams hook and libraries like nux.47ng.com offer the most efficient and maintainable solutions. By carefully managing the URL, you can create robust, shareable, and user-friendly web applications.

Was this summary helpful?

Quick Actions

Watch on YouTube

Related Summaries

No related summaries found.

Summarize a New YouTube Video

Enter a YouTube video URL below to get a quick summary and key takeaways.