Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. import { useEffect, useRef, useState } from 'react'
  2.  
  3. /*
  4. If you attempt to set some state after asynchronous request it may happen that component you wish to set state on has been unmounted.
  5. This will trigger "Warning: Can’t call setState (or forceUpdate) on an unmounted component." warning.
  6. This hooks is `useState` hook which prevents setting state on an unmounted component
  7. Usage:
  8. const [myState, mySafeSetState] = useSafeState(initialValue)
  9. */
  10. const useSafeState = (initialValue) => {
  11. const _isMounted = useRef() // useRef to memorize if the component is mounted between renders
  12. const [state, setState] = useState(initialValue)
  13. useEffect(() => {
  14. _isMounted.current = true
  15. return () => {
  16. _isMounted.current = false
  17. }
  18. })
  19. const safeSetState = (...args) => {
  20. if(_isMounted.current) { // do not call setState if the component already unmounted
  21. setState(...args)
  22. }
  23. }
  24. return [state, safeSetState]
  25. }
  26.  
  27. export default useSafeState
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement