Skip to content

Commit

Permalink
Update RulesOfHooks with useEvent rules
Browse files Browse the repository at this point in the history
This update to the lint rule checks that functions created with
`useEvent` can only be invoked in a `useEffect`callback or closure.
They can't be passed down directly as a reference to child components.
  • Loading branch information
poteto committed Sep 16, 2022
1 parent be966fd commit 1fae1ad
Show file tree
Hide file tree
Showing 2 changed files with 206 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,36 @@ const tests = {
const [myState, setMyState] = useState(null);
}
`,
`
// Valid because functions created with useEvent can be called in a useEffect.
function MyComponent({ theme }) {
const onClick = useEvent(() => {
showNotification(theme);
});
useEffect(() => {
onClick();
});
}
`,
`
// Valid because functions created with useEvent can be called in closures.
function MyComponent({ theme }) {
const onClick = useEvent(() => {
showNotification(theme);
});
return <Child onClick={() => onClick()}></Child>;
}
`,
`
// Valid because functions created with useEvent can be called in closures.
function MyComponent({ theme }) {
const onClick = useEvent(() => {
showNotification(theme);
});
const onClick2 = () => { onClick() };
return <Child onClick={onClick2}></Child>;
}
`,
],
invalid: [
{
Expand Down Expand Up @@ -449,7 +479,7 @@ const tests = {
},
{
code: `
// This is a false positive (it's valid) that unfortunately
// This is a false positive (it's valid) that unfortunately
// we cannot avoid. Prefer to rename it to not start with "use"
class Foo extends Component {
render() {
Expand Down Expand Up @@ -971,6 +1001,70 @@ const tests = {
`,
errors: [classError('useState')],
},
{
code: `
function MyComponent({ theme }) {
const onClick = useEvent(() => {
showNotification(theme);
});
return <Child onClick={onClick}></Child>;
}
`,
errors: [useEventError()],
},
{
code: `
function MyComponent({ theme }) {
const onClick = useEvent(() => {
showNotification(theme);
});
let jsx;
if (theme === 'dark') {
jsx = <Child onClick={onClick} className="dark" />
} else {
jsx = <Child onClick={onClick} className="light" />
}
const jsx2 = theme === 'dark'
? <Child onClick={onClick} className="dark" />
: <Child onClick={onClick} className="light" />;
return jsx;
}
`,
errors: [
useEventError(),
useEventError(),
useEventError(),
useEventError(),
],
},
{
code: `
function MyComponent({ theme }) {
const onClick = useEvent(() => {
showNotification(theme);
});
return <Child onClick={onClick.bind(null)}></Child>;
}
`,
errors: [useEventError()],
},
{
code: `
function MyComponent({ theme }) {
const onClick = useEvent(() => {
showNotification(theme);
});
useMyHook(() => {
onClick();
});
const customOnClick = useMyHook(() => {
onClick();
});
}
`,
errors: [useEventError(), useEventError()],
},
],
};

Expand Down Expand Up @@ -1031,6 +1125,14 @@ function classError(hook) {
};
}

function useEventError() {
return {
message:
'Functions created with React Hook "useEvent" must only be invoked in a ' +
'"useEffect" or closure.',
};
}

// For easier local testing
if (!process.env.CI) {
let only = [];
Expand Down
103 changes: 103 additions & 0 deletions packages/eslint-plugin-react-hooks/src/RulesOfHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,34 @@ function isInsideComponentOrHook(node) {
return false;
}

function isUseEventIdentifier(node) {
return node.name === 'useEvent' || node.name === 'experimental_useEvent';
}

function isUseEventVariableDeclarator(node) {
return (
node.type === 'VariableDeclarator' &&
node.init &&
node.init.type === 'CallExpression' &&
node.init.callee.type === 'Identifier' &&
isUseEventIdentifier(node.init.callee)
);
}

function recursivelyFindVariableInScope(scope, name) {
const stack = [scope];
while (stack.length > 0) {
const currScope = stack.pop();
const variable = currScope.set.get(name);
if (variable != null) {
return variable;
}
if (currScope.upper != null) {
stack.push(currScope.upper);
}
}
}

export default {
meta: {
type: 'problem',
Expand All @@ -110,8 +138,28 @@ export default {
},
},
create(context) {
const MAX_USE_EVENT_ANCESTOR_DEPTH = 5;
const codePathReactHooksMapStack = [];
const codePathSegmentStack = [];

// Recursively walk up the current scope until we find the function
// definition, and report if the function was created with useEvent.
function reportOnUseEventDirectReferences(scope, ident) {
const variable = recursivelyFindVariableInScope(scope, ident.name);
if (variable != null) {
variable.defs.forEach(def => {
if (isUseEventVariableDeclarator(def.node)) {
context.report({
node: ident,
message:
'Functions created with React Hook "useEvent" must only be invoked in a ' +
'"useEffect" or closure.',
});
}
});
}
}

return {
// Maintain code segment path stack as we traverse.
onCodePathSegmentStart: segment => codePathSegmentStack.push(segment),
Expand Down Expand Up @@ -522,6 +570,61 @@ export default {
}
reactHooks.push(node.callee);
}

// Check if a function created with useEvent is invoked within
// a useEffect or closure.
const scope = context.getScope();
const variable = recursivelyFindVariableInScope(
scope,
node.callee.name,
);
if (variable) {
const isUseEvent = variable.defs.some(def => {
return isUseEventVariableDeclarator(def.node);
});
if (isUseEvent) {
let depth = 0;
for (const ancestor of context.getAncestors()) {
// For performance reasons we don't want to walk up
// every single ancestor node.
if (depth++ > MAX_USE_EVENT_ANCESTOR_DEPTH) {
break;
}
if (
ancestor.type === 'CallExpression' &&
ancestor.callee.name !== 'useEffect'
) {
context.report({
node: node.callee,
message:
'Functions created with React Hook "useEvent" must only be invoked in a ' +
'"useEffect" or closure.',
});
break;
}
}
}
}
},

JSXExpressionContainer(node) {
const scope = context.getScope();
// <Child onClick={onClick} />
if (node.expression.type === 'Identifier') {
reportOnUseEventDirectReferences(scope, node.expression);
}

// <Child onClick={onClick.bind(null)} />
if (
node.expression.type === 'CallExpression' &&
node.expression.callee.type === 'MemberExpression' &&
node.expression.callee.object.type === 'Identifier'
) {
reportOnUseEventDirectReferences(
scope,
node.expression.callee.object,
);
}
},
};
},
Expand Down

0 comments on commit 1fae1ad

Please sign in to comment.