nova-betterchat/src/hooks/useSaveToLocalStorage.ts
Jing Hua 4fa5c14734 feat: performance optimisation
fixes partially #9 and #16
2023-03-05 22:59:31 +08:00

20 lines
516 B
TypeScript

import React, { useEffect, useRef } from 'react';
import useStore from '@store/store';
const useSaveToLocalStorage = () => {
const chatsRef = useRef(useStore.getState().chats);
useEffect(() => {
const unsubscribe = useStore.subscribe((state) => {
if (chatsRef && chatsRef.current !== state.chats) {
chatsRef.current = state.chats;
localStorage.setItem('chats', JSON.stringify(state.chats));
}
});
return unsubscribe;
}, []);
};
export default useSaveToLocalStorage;