Skip to content

Instantly share code, notes, and snippets.

@fnky
Last active November 27, 2019 10:56
Show Gist options
  • Save fnky/7c96c7fa3ec0e36796675f83c6635e48 to your computer and use it in GitHub Desktop.
Save fnky/7c96c7fa3ec0e36796675f83c6635e48 to your computer and use it in GitHub Desktop.
History provider with useState / useRef
import React from 'react';
import { createBrowserHistory } from 'history';
export const historyContext = React.createContext(null);
const HistoryContextProvider = historyContext.Provider;
// This is initialized at the time the file/module is imported, and not on component mount.
const history = createBrowserHistory();
export function History(props) {
return <HistoryContextProvider value={history} {...props} />;
}
import React from 'react';
import { createBrowserHistory } from 'history';
export const historyContext = React.createContext(null);
const HistoryContextProvider = historyContext.Provider;
export function History(props) {
// Initialize the instance in useState. Initialized on mount. Available from first render.
const [history] = React.useState(() => createBrowserHistory());
return <HistoryContextProvider value={history} {...props} />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment