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

Resource leak with useHookstate #381

Open
zroug opened this issue Mar 17, 2023 · 2 comments
Open

Resource leak with useHookstate #381

zroug opened this issue Mar 17, 2023 · 2 comments
Labels
bug Something isn't working

Comments

@zroug
Copy link

zroug commented Mar 17, 2023

onDestroy is not called for every onCreate / onInit, resulting in the associated resources not being reclaimed. This happens when a component is instantiated multiple times and may be related to React Strict Mode.

Steps to reproduce:

  1. Open the example here or use the code from below.
  2. Click the button repeatedly and see how the number of Hookstate instances goes to infinity.

Code:

import React from "react";
import { useHookstate, hookstate } from "@hookstate/core";

export default function App() {
  const component = useHookstate(true);
  const count = useHookstate(instanceCounter);
  return (
    <div className="App">
      <button onClick={() => component.set((c) => !c)}>Click</button>
      {component.get() ? <h1>Component 1</h1> : <Component />}
      Number of Hookstate instances for `state`: {count.get()}
    </div>
  );
}

function Component() {
  const state = useHookstate(2, countInstanceExtension);
  return <h1>Component {state.get()}</h1>;
}

const countInstanceExtension = () => ({
  onInit: () => {
    // setTimeout is to avoid setting counter while rendering.
    setTimeout(() => instanceCounter.set((x) => x + 1));
  },
  onDestroy: () => {
    setTimeout(() => instanceCounter.set((x) => x - 1));
  },
});

let instanceCounter = hookstate(0);
@avkonst
Copy link
Owner

avkonst commented Mar 19, 2023

Hi, very interesting. Hookstate can handle strict mode and can do the related double init/destroy. It seems like it is definitely caused by the strict mode.

@avkonst avkonst added the bug Something isn't working label Mar 19, 2023
@avkonst
Copy link
Owner

avkonst commented Apr 1, 2023

I have debugged it. It happens only in StrictMode in development. The fix is possible but may affect extensions callbacks calls behavior. I will try to implement something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants