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

Detect use of useState inside useEffect #16

Closed
linonetwo opened this issue Apr 18, 2019 · 3 comments
Closed

Detect use of useState inside useEffect #16

linonetwo opened this issue Apr 18, 2019 · 3 comments

Comments

@linonetwo
Copy link

This will cause lots of rerender, without warning.

@Gelio
Copy link
Owner

Gelio commented Apr 18, 2019

Thanks for posting an issue 🙂

Are you sure that useState inside useEffect does not result in any violations? For me, the following snippet:

function MyComponent() {
  React.useEffect(() => {
    React.useState(() => {

    })
  })
}

results in a rightful rule violation:

image

Could you share a snippet of this case that does not result in a rule violation? 🙂

@linonetwo
Copy link
Author

linonetwo commented Apr 19, 2019

Hi, I just found that, in some case likes:

  const [currentRenderCounter, setRenderCounter] = useState(0);
  useEffect(() => {
    if (shouldRender) {
      setRenderCounter(counter => counter + 1);
      console.log(currentRenderCounter);
...

Will cause infinite loop of rendering.

But in some case, it's fine to use state in useEffect... I'm still confise why some times it works.

The safe way is to useRef:

  const renderCounter = useRef(0);

  useEffect(() => {
    if (shouldRender) {
      renderCounter.current += 1;
      console.log(renderCounter.current);
...

@Gelio
Copy link
Owner

Gelio commented Apr 19, 2019

I am not convinced that this is a responsibility of the linter to report such behavior 🙂 Statically analyzing the code would not result in enough information to determine that setCounterRender will cause an endless loop.

Moreover, in some cases, the code snippet you provided is the wanted behavior, as in some cases shouldRender may be falsy. That is why it would not be easy to stop such behavior even during runtime.

All in all, I have no easy idea on how to implement such verification, therefore I am closing this issue. If you, or anyone else, has an implementation idea, feel free to create a PR 🙂

@Gelio Gelio closed this as completed Apr 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants