1.0.2 • Published 2 years ago

react-custom-hooked v1.0.2

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

react-custom-hooked

UseIsMounted

Assume we have a component that loads some data when it's mounted:

import React from 'react'

function MyComponent() {
  const [data, setData] = React.useState(null)
  React.useEffect(() => {
    fetchData().then((result) => {
      setData(result)
    })
  }, [])
  // ...
}

If this component is unmounted for some reason before the fetchData() resolves. Then, when it does, it will try to call setData of the unmounted state. This will cause the following React warning:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

The warning indicates that we should cancel the asynchronous task, but it's not always possible/easy to do so. That's where the useIsMounted hooks is useful:

import React from 'react'
+ import {useIsMounted} from 'react-tidy'

function MyComponent() {
  const [data, setData] = React.useState(null)
+  const isMounted = useIsMounted()
  React.useEffect(() => {
    fetchData().then((result) => {
+      if (isMounted()) {
        setData(result)
+      }
    })
  }, [])
  // ...
}

Now we will not call setData if the component has been unmounted.

UseRefresh

import React from 'react'
import {useRefresh} from 'react-tidy'

function App() {
  const refresh = useRefresh()
  return (
    <p>
      The time is {new Date()} <button onClick={refresh}>Refresh</button>
    </p>
  )
}