Skip to content

Instantly share code, notes, and snippets.

@elderbas
Last active May 5, 2021 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elderbas/70722378373885c1aea7d4381d5e7069 to your computer and use it in GitHub Desktop.
Save elderbas/70722378373885c1aea7d4381d5e7069 to your computer and use it in GitHub Desktop.
codemodscript to refactor `useEffect` with empty array to `useEffectOnce` without an array arg
module.exports = function (file, api) {
const j = api.jscodeshift;
const { CallExpression, Identifier } = j;
return (
j(file.source)
.find(CallExpression, {
callee: {
name: "useEffect",
},
})
.filter((node) => {
return (
// is a useEffect with 2 arguments
node.value.arguments.length === 2 &&
// 2nd argument is an array type
node.value.arguments[1].type === "ArrayExpression" &&
// said array argument is an empty array
node.value.arguments[1].elements.length === 0
);
})
// operate on useEffects that have an empty dependency array
.forEach((node) => {
// refactor the function name
node.value.callee.name = "useEffectOnce";
// remove the 2nd argument to this function
node.value.arguments = [node.value.arguments[0]];
})
.toSource()
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment