{"id":26021216,"url":"https://github.com/teclone/react-use-effect-cleaner","last_synced_at":"2025-03-06T08:50:31.208Z","repository":{"id":153286549,"uuid":"628649134","full_name":"teclone/react-use-effect-cleaner","owner":"teclone","description":"Utility package for executing clean asynchronous stuffs in React use effect hook","archived":false,"fork":false,"pushed_at":"2023-10-25T08:36:07.000Z","size":647,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-04-25T17:05:20.505Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/teclone.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2023-04-16T15:53:11.000Z","updated_at":"2023-04-18T07:18:10.000Z","dependencies_parsed_at":"2023-10-16T04:34:29.398Z","dependency_job_id":"74ea6dba-fe1a-4704-8151-37e9a1a848e8","html_url":"https://github.com/teclone/react-use-effect-cleaner","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teclone%2Freact-use-effect-cleaner","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teclone%2Freact-use-effect-cleaner/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teclone%2Freact-use-effect-cleaner/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/teclone%2Freact-use-effect-cleaner/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/teclone","download_url":"https://codeload.github.com/teclone/react-use-effect-cleaner/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242179280,"owners_count":20084940,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-06T08:50:30.749Z","updated_at":"2025-03-06T08:50:31.198Z","avatar_url":"https://github.com/teclone.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# React Use Effect Cleaner\n\nFamiliar with the `Can't perform a React state update on an unmounted component` error? this tiny package is to help solve that as well prevent stalled state updates in react components.\n\nExecution of asynchronous/scheduled calls such as setTimeout and setIntervals in React useEffect hook has some quite interesting gotchas. First is the possibility of running state updates even when the component had been unmounted.\n\nSecond is the possibility of running state updates from an effect that has already stalled, because you failed to clean the effect properly.\n\nThird is unoptimization of network requests. Why make network requests when the effect is stalled?\n\nFinally, these things can result to memory leaks, infinite loop/lifetime execution of code in client applications.\n\nThese three problems can be seen in the codebase below\n\n```tsx\nimport { useEffect, useState } from 'react';\n\n// sample asynchronous request\nconst getUserProfile = (userId) =\u003e Promise.resolve({ id: userId });\n\nconst Profile = ({ userId }) =\u003e {\n  const [user, setUser] = useState(0);\n\n  useEffect(() =\u003e {\n    getUserProfile(userId).then(setValue);\n  }, [userId]);\n\n  return (\n    \u003cdiv\u003e\n      \u003cp\u003eUserid: {user.id}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n};\n```\n\nIf the Profile component gets unmounted, there is possibility that the call to get a user profile is still in progress, and would trigger a state update by the time it is resolved late in the application.\n\nThere is also a probability that the data of user A been shown as the data of user B.\n\nFinally, could we abort a network request when the effect is no longer valid? for instance, when the `userId` changes or when the component gets unmounted\n\n## Installation\n\n```bash\nnpm install @teclone/react-use-effect-cleaner\n```\n\n## Sample Usage with Api Request Cleanup\n\nBelow is how to utilize this module to solve the problems of the code shown earlier.\n\n```tsx\nimport { useState, useEffect } from 'react';\nimport { createEffectCleaner } from '@teclone/react-use-effect-cleaner';\n\n// sample asynchronous request\nconst getUserProfile = (userId, abortSignal) =\u003e Promise.resolve({ id: userId });\n\nconst Profile = ({ userId }) =\u003e {\n  const [user, setUser] = useState(0);\n\n  useEffect(() =\u003e {\n    const abortController = new AbortController();\n    const effects = createEffectCleaner(\n      {\n        setUser,\n      },\n      { abortController }\n    );\n\n    getUserProfile(userId, abortController.signal).then(effects.setUser);\n\n    // return the cleaner\n    return effects.clean();\n  }, [userId]);\n\n  return (\n    \u003cdiv\u003e\n      \u003cp\u003eUserid: {user.id}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n};\n```\n\nIf the component is unmounted, or the `userId` changes, the effect cleaner will try to abort the request earlier. It will also prevent the `setUser` state change from executing.\n\nThe module utilizes the Proxy web api to create a middleware for all state modifiers.\n\nAbortController is supported by popular request client libraries including Fetch and Axios.\n\n## Sample Usage with SetTimeout/SetInterval Cleanup\n\nBelow is an example of how to use the createEffectCleaner to clean up setTimeouts or setInterval.\n\n```tsx\nimport { useState, useEffect } from 'react';\nimport { createEffectCleaner } from '@teclone/react-use-effect-cleaner';\n\n// sample asynchronous request\nconst getUserProfile = (userId, abortSignal) =\u003e Promise.resolve({ id: userId });\n\nconst Profile = ({ userId }) =\u003e {\n  const [count, setCount] = useState(0);\n\n  useEffect(() =\u003e {\n    const timoutIds = { count: 0 };\n    const intervalIds = { count: 0 };\n\n    // create effects\n    const effects = createEffectCleaner(\n      {\n        setCount,\n      },\n      { timeoutIds, intervalIds }\n    );\n\n    timeoutIds.count = setTimeout(() =\u003e {\n      effects.setCount((count) =\u003e count + 1);\n    }, 10000);\n\n    intervalIds.count = setInterval(() =\u003e {\n      effects.setCount((count) =\u003e count + 1);\n    }, 1000);\n\n    // return the cleaner\n    return effects.clean();\n  }, [userId]);\n\n  return (\n    \u003cdiv\u003e\n      \u003cp\u003eCurrent Count: {count}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n};\n```\n\n### Interface\n\nThe package has only one export.\n\n#### createEffectCleaner(stateModifiers, opts?)\n\n- `stateModifiers`: an object of stateModifiers that should be proxied.\n\n- `opts`: optional object with the following optional properties for cancelling or aborting networking/api requests\n\n  - `abortController` - axios, fetch and others\n  - `cancelTokenSource` - provide if your networking client is legacy axios\n  - `timeoutIds` - an object store containing timeout ids from `setTimeout`. Note that the object must be treated as a store and modifications to the timoutIds must be made on the store for this to work. (pass by reference).\n  - `intervalIds` - an object store containing interval ids from `setInterval`. Just like timeoutIds, the ids must be passed by reference.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fteclone%2Freact-use-effect-cleaner","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fteclone%2Freact-use-effect-cleaner","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fteclone%2Freact-use-effect-cleaner/lists"}