In this blog post, we’ll show you How to Use Remix useBlocker and useResolvedPath Hooks on Your Shopify Remix App.
useBlocker
The useBlocker hook allows you to prevent the user from navigating away from the current location, and present them with a custom UI to allow them to confirm the navigation.
Example:
Here is the code provided to use useBlocker while user is navigating away from their location.
function ImportantForm() {
const [value, setValue] = React.useState("");
const blocker = useBlocker(
({ currentLocation, nextLocation }) =>
value !== "" &&
currentLocation.pathname !== nextLocation.pathname
);
return (
<Form method="post">
<label>
Enter some important data:
<input
name="data"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</label>
<button type="submit">Save</button>
{blocker.state === "blocked" ? (
<div>
<p>Are you sure you want to leave?</p>
<button onClick={() => blocker.proceed()}>
Proceed
</button>
<button onClick={() => blocker.reset()}>
Cancel
</button>
</div>
) : null}
</Form>
);
}
useResolvedPath
It resolves the pathname of the given to value against the pathname of the current location and returns a Path object.
Example:
import { useResolvedPath } from "@remix-run/react";
function SomeComponent() {
const path = useResolvedPath("../some/where");
path.pathname;
path.search;
path.hash;
// ...
}
This is useful when building links from relative values and used internally for <navlink>.
Conclusion:
The useBlocker and useResolvedPath hooks are invaluable tools for building robust and user-friendly Shopify Remix applications. You can use useBlocker and useResolvedPath for a better user experience and better app results.
Learn about other hooks in Remix