The useBack hook returns a function that navigates back to the previous page in the browser history.
Usage
import { useBack } from "@refinedev/core";
const back = useBack();
Return Value
Returns a function that when called, navigates back to the previous page.
Function to navigate back to the previous page in the browser history.
Examples
Basic Usage
import { useBack } from "@refinedev/core";
const MyComponent = () => {
const back = useBack();
return (
<button onClick={back}>
Go Back
</button>
);
};
import { useBack } from "@refinedev/core";
import { Form, Button } from "antd";
const EditPage = () => {
const back = useBack();
const handleCancel = () => {
if (window.confirm("Discard changes?")) {
back();
}
};
return (
<Form>
{/* form fields */}
<Button onClick={handleCancel}>Cancel</Button>
<Button type="primary" htmlType="submit">Save</Button>
</Form>
);
};
import { useBack } from "@refinedev/core";
const DetailPage = () => {
const back = useBack();
return (
<div>
<div style={{ marginBottom: 16 }}>
<button onClick={back}>
← Back to List
</button>
</div>
{/* page content */}
</div>
);
};
In a Modal
import { useBack } from "@refinedev/core";
import { Modal } from "antd";
const DetailModal = ({ visible }: { visible: boolean }) => {
const back = useBack();
return (
<Modal
visible={visible}
onCancel={back}
title="Details"
>
{/* modal content */}
</Modal>
);
};
Conditional Navigation
import { useBack } from "@refinedev/core";
import { useState } from "react";
const FormPage = () => {
const back = useBack();
const [hasChanges, setHasChanges] = useState(false);
const handleBack = () => {
if (hasChanges) {
if (window.confirm("You have unsaved changes. Are you sure you want to leave?")) {
back();
}
} else {
back();
}
};
return (
<div>
<button onClick={handleBack}>Back</button>
{/* form that sets hasChanges */}
</div>
);
};
Notes
- This hook uses the browser’s history API to navigate back
- If there’s no previous page in the history, the behavior depends on the browser (typically does nothing)
- This is equivalent to calling
window.history.back() but integrated with your router provider
See Also
- useGo - Programmatic navigation with more control
- useNavigation - Higher-level navigation methods
- useParsed - Parse current route information