diff --git a/x-pack/plugins/apm/public/hooks/useLocalStorage.ts b/x-pack/plugins/apm/public/hooks/useLocalStorage.ts index dc07b89ec7807..bf66d364dbcc6 100644 --- a/x-pack/plugins/apm/public/hooks/useLocalStorage.ts +++ b/x-pack/plugins/apm/public/hooks/useLocalStorage.ts @@ -5,12 +5,10 @@ * 2.0. */ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useCallback } from 'react'; export function useLocalStorage(key: string, defaultValue: T) { - const [item, setItem] = useState(getFromStorage()); - - function getFromStorage() { + const getFromStorage = useCallback(() => { const storedItem = window.localStorage.getItem(key); let toStore: T = defaultValue; @@ -26,7 +24,9 @@ export function useLocalStorage(key: string, defaultValue: T) { } return toStore; - } + }, [key, defaultValue]); + + const [item, setItem] = useState(getFromStorage()); const updateFromStorage = () => { const storedItem = getFromStorage(); @@ -51,5 +51,9 @@ export function useLocalStorage(key: string, defaultValue: T) { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + useEffect(() => { + setItem(getFromStorage()); + }, [getFromStorage]); + return [item, saveToStorage] as const; }