Skip to content

Commit

Permalink
consistent-function-scoping: Ignore within useEffect in Reac… (#588)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker authored Mar 11, 2020
1 parent 92f3f3d commit 7126d6d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
22 changes: 21 additions & 1 deletion rules/consistent-function-scoping.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,26 @@ function checkReferences(scope, parent, scopeManager) {
);
}

// https://reactjs.org/docs/hooks-reference.html
const reactHooks = new Set([
'useState',
'useEffect',
'useContext',
'useReducer',
'useCallback',
'useMemo',
'useRef',
'useImperativeHandle',
'useLayoutEffect',
'useDebugValue'
]);
const isReactHook = scope =>
scope.block &&
scope.block.parent &&
scope.block.parent.callee &&
scope.block.parent.callee.type === 'Identifier' &&
reactHooks.has(scope.block.parent.callee.name);

function checkNode(node, scopeManager) {
const scope = scopeManager.acquire(node);
if (!scope) {
Expand Down Expand Up @@ -102,7 +122,7 @@ function checkNode(node, scopeManager) {
}

const parentScope = scopeManager.acquire(parentNode);
if (!parentScope || parentScope.type === 'global') {
if (!parentScope || parentScope.type === 'global' || isReactHook(parentScope)) {
return true;
}

Expand Down
18 changes: 18 additions & 0 deletions test/consistent-function-scoping.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,12 @@ ruleTester.run('consistent-function-scoping', rule, {
return Bar;
};
`,
// React Hooks
outdent`
useEffect(() => {
function foo() {}
}, [])
`,
// #391
outdent`
const enrichErrors = (packageName, cliArgs, f) => async (...args) => {
Expand Down Expand Up @@ -377,6 +383,18 @@ ruleTester.run('consistent-function-scoping', rule, {
}
`,
errors: [createError({name: 'doBar'})]
},
// React Hooks
{
code: outdent`
useEffect(() => {
function foo() {
function bar() {
}
}
}, [])
`,
errors: [createError({name: 'bar'})]
}
]
});
Expand Down

0 comments on commit 7126d6d

Please sign in to comment.