I created a history provider with React context. I use it to hide elements on a page when the user comes from another specific page.
- Create the Provider and the context, and a hook to facilitate the usage:
// src/common/providers/history-provider.tsx
import { createContext, FC, ReactNode, useContext, useEffect, useState } from 'react';
import { useRouter } from 'next/router';
const HistoryContext = createContext<string[]>([]);
interface Props {
children: ReactNode;
}
export const HistoryProvider: FC<Props> = ({ children }) => {
const { asPath } = useRouter();
const [history, setHistory] = useState<string[]>([]);
useEffect(() => {
setHistory((previous) => [...previous, asPath]);
}, [asPath]);
return <HistoryContext.Provider value={history}>{children}</HistoryContext.Provider>;
};
export function useHistory(): string[] {
return useContext(HistoryContext);
}
- Wrap your application with the provider:
// src/pages/_app.tsx
import type { AppProps } from 'next/app';
import { RootLayout } from '@/common/layouts/root';
import 'react-toastify/dist/ReactToastify.css';
import { HistoryProvider } from 'common/providers/history-provider';
export default function App({ Component, pageProps }: AppProps) {
return (
<RootLayout>
<HistoryProvider>
<Component {...pageProps} />
</HistoryProvider>
</RootLayout>
);
}
- Use the hook
useHistory
to get the path history in your component:
// src/features/x/components/component-x.tsx
export const ComponentX: FC = () => {
const history = useHistory();
const comingFromAdding = (): boolean => {
if (history.length < 2) return false;
return !history.at(-2)?.includes('add');
};
if(comingFromAdding()) // do something...
// ...
}