Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

consistent-function-scoping: Ignore within useEffect in React Hooks #588

Merged
merged 7 commits into from
Mar 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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