Skip to content

Commit

Permalink
Treat React.useRef/useState/useReducer as static too
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon committed Feb 19, 2019
1 parent 5d2c991 commit e0203cb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,9 @@ const tests = {
const definitelyRef2 = useRef();
const maybeRef1 = useSomeOtherRefyThing();
const [state1, setState1] = useState();
const [state2, setState2] = useState();
const [state2, setState2] = React.useState();
const [state3, dispatch1] = useReducer();
const [state4, dispatch2] = useReducer();
const [state4, dispatch2] = React.useReducer();
const [state5, maybeSetState] = useFunnyState();
const [state6, maybeDispatch] = useFunnyReducer();
function mySetState() {}
Expand Down Expand Up @@ -336,9 +336,9 @@ const tests = {
const maybeRef1 = useSomeOtherRefyThing();
const [state1, setState1] = useState();
const [state2, setState2] = useState();
const [state2, setState2] = React.useState();
const [state3, dispatch1] = useReducer();
const [state4, dispatch2] = useReducer();
const [state4, dispatch2] = React.useReducer();
const [state5, maybeSetState] = useFunnyState();
const [state6, maybeDispatch] = useFunnyReducer();
Expand Down
34 changes: 22 additions & 12 deletions packages/eslint-plugin-react-hooks/src/ReactiveDeps.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,23 +199,33 @@ export default {
if (def != null && def.node.init != null) {
const init = def.node.init;
if (init.callee != null) {
let callee = init.callee;
if (
init.callee.name === 'useRef' &&
def.node.id.type === 'Identifier'
) {
info.isKnownToBeStatic = true;
} else if (
init.callee.name === 'useState' ||
init.callee.name === 'useReducer'
callee.type === 'MemberExpression' &&
callee.object.name === 'React' &&
callee.property != null
) {
callee = callee.property;
}
if (callee.type === 'Identifier') {
if (
def.node.id.type === 'ArrayPattern' &&
def.node.id.elements.length === 2 &&
Array.isArray(reference.resolved.identifiers) &&
def.node.id.elements[1] ===
reference.resolved.identifiers[0]
callee.name === 'useRef' &&
def.node.id.type === 'Identifier'
) {
info.isKnownToBeStatic = true;
} else if (
callee.name === 'useState' ||
callee.name === 'useReducer'
) {
if (
def.node.id.type === 'ArrayPattern' &&
def.node.id.elements.length === 2 &&
Array.isArray(reference.resolved.identifiers) &&
def.node.id.elements[1] ===
reference.resolved.identifiers[0]
) {
info.isKnownToBeStatic = true;
}
}
}
}
Expand Down

0 comments on commit e0203cb

Please sign in to comment.