/
githubmirror
/
amphtml
Обзор
Документация
Войти
/
githubmirror
/
amphtml
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
src/preact/hooks/useStateSafe.ts
34 строки
835 B
Scott Rippey
✨ [bento-list] Implemented bento-list component (#37360)
23 фев 2022, 21:06
Не верифицирован
23 фев 2022, 21:06
483540b
Код
Авторство
О чём код?
import type {StateUpdater} from 'preact/compat'; import {useCallback, useEffect, useRef, useState} from '#preact'; /** * Same as useState, but ignores setState once the component is unmounted. * * This avoids React's "Can't perform a React state update on an unmounted component" console error */ export function useStateSafe<S>( initialState: S | (() => S) ): readonly [S, StateUpdater<S>] { const isMounted = useRef(false); useEffect(() => { isMounted.current = true; return () => { isMounted.current = false; }; }, []); const [state, setState] = useState(initialState); const setStateSafe = useCallback<StateUpdater<S>>( (newState) => { if (!isMounted.current) { return; } setState(newState); }, [setState] ); return [state, setStateSafe] as const; }