diff --git a/x-pack/plugins/monitoring/public/application/contexts/global_state_context.tsx b/x-pack/plugins/monitoring/public/application/contexts/global_state_context.tsx index 71180f2c2c92d..7d5ab0be65033 100644 --- a/x-pack/plugins/monitoring/public/application/contexts/global_state_context.tsx +++ b/x-pack/plugins/monitoring/public/application/contexts/global_state_context.tsx @@ -4,9 +4,10 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import React, { createContext } from 'react'; +import React, { createContext, useState } from 'react'; import type { TimeRange } from '@kbn/es-query'; import { RefreshInterval } from '@kbn/data-plugin/public'; +import useUnmount from 'react-use/lib/useUnmount'; import { GlobalState } from '../../url_state'; import { MonitoringStartPluginDependencies, MonitoringStartServices } from '../../types'; import { Legacy } from '../../legacy_shims'; @@ -42,9 +43,11 @@ export const GlobalStateProvider: React.FC = ({ children, }) => { const localState: State = {}; - const state = new GlobalState(query, toasts, localState as { [key: string]: unknown }); + const [globalState] = useState( + () => new GlobalState(query, toasts, localState as { [key: string]: unknown }) + ); - const initialState: any = state.getState(); + const initialState: any = globalState.getState(); for (const key in initialState) { if (!initialState.hasOwnProperty(key)) { continue; @@ -55,7 +58,7 @@ export const GlobalStateProvider: React.FC = ({ localState.save = () => { const newState = { ...localState }; delete newState.save; - state.setState(newState); + globalState.setState(newState); }; // default to an active refresh interval if it's not conflicting with user-defined values @@ -65,5 +68,9 @@ export const GlobalStateProvider: React.FC = ({ localState.save(); } + useUnmount(() => { + globalState.destroy(); + }); + return {children}; };