Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useEffect, useRef, useState } from 'react'
- /*
- If you attempt to set some state after asynchronous request it may happen that component you wish to set state on has been unmounted.
- This will trigger "Warning: Canβt call setState (or forceUpdate) on an unmounted component." warning.
- This hooks is `useState` hook which prevents setting state on an unmounted component
- Usage:
- const [myState, mySafeSetState] = useSafeState(initialValue)
- */
- const useSafeState = (initialValue) => {
- const _isMounted = useRef() // useRef to memorize if the component is mounted between renders
- const [state, setState] = useState(initialValue)
- useEffect(() => {
- _isMounted.current = true
- return () => {
- _isMounted.current = false
- }
- })
- const safeSetState = (...args) => {
- if(_isMounted.current) { // do not call setState if the component already unmounted
- setState(...args)
- }
- }
- return [state, safeSetState]
- }
- export default useSafeState
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement