Before we delve deep into more intricate examples, let’s start with a straightforward one—a React functional component designed to toggle between “On” and “Off” states. This toggle switch initializes and updates its state based on the URL hash.
import React, { useEffect, useState } from 'react';
// Function to fetch the hash value from the URL
const getHash = () =>
typeof window !== 'undefined'
? decodeURIComponent(window.location.hash.replace("#", ""))
: undefined;
const SwitchComponent = () => {
// Initialize state from the URL hash
const [state, setState] = useState(getHash() === 'on' ? 'On' : 'Off');
// Use useEffect to set up an event listener for hash changes
useEffect(() => {
const handleHashChange = () => {
// Update the state based on the new hash value
setState(getHash() === 'on' ? 'On' : 'Off');
};
// Attach the hashchange event listener
window.addEventListener('hashchange', handleHashChange);
// Cleanup by removing the event listener when the component unmounts
return () => {
window.removeEventListener('hashchange', handleHashChange);
};
}, []);
// Render the component
return <div>{`Switch is ${state}`}</div>;
};
To browse to this toggle switch component, you can navigate to a URL like:
http://example.com/switch#on
http://example.com/switch#off
window.location.hash = newStateValue
.hashchange
event on the window object to sync our state with the URL hash.import React, { useEffect, useState } from 'react';
// Function to fetch hash value from URL
const getHash = () =>
typeof window !== 'undefined'
? decodeURIComponent(window.location.hash.replace("#", ""))
: undefined;
const CookieCatalog = () => {
const [selectedCookie, setSelectedCookie] = useState(getHash());
useEffect(() => {
const handleHashChange = () => {
const newCookie = getHash();
setSelectedCookie(newCookie);
};
window.addEventListener('hashchange', handleHashChange);
return () => {
window.removeEventListener('hashchange', handleHashChange);
};
}, []);
const cookies = [
{id: 'chocolate', name: 'Chocolate Chip'},
{id: 'oatmeal', name: 'Oatmeal Raisin'},
{id: 'sugar', name: 'Sugar Cookie'},
{id: 'ginger', name: 'Gingerbread'}
];
const displayCookie = () => {
const foundCookie = cookies.find(cookie => cookie.id === selectedCookie);
return foundCookie ? foundCookie.name : 'Please select a cookie from the list.';
};
return (
<div>
<h1>Cookie Catalog</h1>
<p>Current Cookie: {displayCookie()}</p>
<ul>
{cookies.map((cookie) => (
<li key={cookie.id}>
<a href={`#${cookie.id}`}>{cookie.name}</a>
</li>
))}
</ul>
</div>
);
};
To browse the cookie catalog, navigate to URLs like:
http://example.com/cookie-catalog#chocolate
http://example.com/cookie-catalog#oatmeal
http://example.com/cookie-catalog#sugar
http://example.com/cookie-catalog#ginger
By following these URLs, you’ll find that the application will display the cookie type according to the URL hash, making it an interactive and dynamic experience.
To encapsulate, managing state in React applications through URL hashes provides a robust yet straightforward mechanism that addresses several facets—enhanced user experience, state persistence, and server-side rendering compatibility. This article delved into two practical examples: a basic toggle switch and a more complex cookie catalog, both leveraging URL hashes for state management.
In these examples, the foundational concept remained consistent: initialize the state based on the current URL hash, update the URL hash to reflect changes in the state, and set up an event listener to keep both in sync. By understanding and implementing these simple steps, one can effectively maintain state across React components, allowing for an interactive, shareable, and resilient user experience.
Whether you’re building something as simple as a toggle switch or as dynamic as an online catalog, URL hashes offer a convenient, easily manageable state solution for your React applications.