Estoy implementando un enlace "useUserPosts", que se supone que debe usarse en varias rutas de mi aplicación.
Como ya tengo un contexto "PostsContext" que vuelve a mostrar mis Tarjetas cuando cambian los datos (totalLikes, totalComments, descripciones, ...), he decidido evitar crear otro llamado "UserPostsContext" cuyo propósito es devolver las publicaciones de los usuarios. formación.
Lo sé, ¿por qué no usar PostsContext en su lugar?...
La respuesta es que, en PostsContext, para evitar problemas de rendimiento, almaceno un mapa (clave, valor) para obtener/actualizar los datos dinámicos de las publicaciones en O(1), algo que solo es útil en mis componentes (entonces , se utiliza para sincronizar tarjetas básicamente)
¿Es posible/una práctica común en React crear ganchos que manejen estados globales sin usar Context API o Redux?
Quiero decir, algo como
// Global State Hook const useUserPosts = (() => { const [posts, setPosts] = useState({}); return ((userId) => [posts[id] ?? [], setPosts]); })(); // Using the Global State Hook function useFetchUserPosts(userId) { const [posts, setPosts] = useUserPosts(userId); const [loading, setLoading] = useState(!posts.length); const [error, setError] = useState(undefined); const cursor = useRef(new Date()); const hasMoreToLoad = useRef(false); const isFirstFetch = useRef(true); const getUserPosts = async () => { // ... } return { posts, loading, error, getUserPosts }; }Nota: mi propósito con esto es:
1. Reproduce some kind of cache 2. Synchronize the fetched data of each stack screen that is mounted in order to reduce backend costs 3. Synchronize user posts deletionsIncluso si creo que crear un nuevo estado global es la mejor solución, si realmente desea evitarlo, puede crear el suyo propio de la siguiente manera:
export class AppState { private static _instance: AppState; public state = new BehaviorSubject<AppStateType>({}); /** * Set app state without erasing the previous values (values not available in the newState param) * */ public setAppState = (newState: AppStateType) => { this.state.next({ ...this.state, ...newState }); }; private constructor() {} public static getInstance(): AppState { if (!AppState._instance) { AppState._instance = new AppState(); } return AppState._instance; } }Con este tipo de tipo:
export type AppStateType = { username?: string; isThingOk?: boolean; arrayOfThing?: Array<MyType>; ... }Y úsalo de esta manera:
const appState = AppState.getInstance(); ... ... appState.setAppState({ isThingOk: data }); ... ... appState.state.subscribe((state: AppStateType) => {// do your thing here});No estoy seguro de que esta sea la mejor manera de crear un estado propio, pero funciona bastante bien. Siéntete libre de adaptarlo a tus necesidades.
Puedo recomendarle que use alguna biblioteca de administración de estado ligero como zustand : https://github.com/pmndrs/zustand .
Con esta biblioteca, puede evitar volver a renderizar y especificar volver a renderizar solo quiere que los datos que desea cambien o cambien de cierta manera con alguna función para comparar el valor antiguo y el nuevo.