'React useContext method scope

I create custom hooks for reading state stores in my applications. const store = useStore(); Which I define as:

const store = new Store();

const StoreContext = createContext(store);
StoreContext.displayName = "StoreContext";

function useStore(): Store {
  const context = useContext(StoreContext);
  if (!context) {
    throw new Error("useStore must be used within MyProvider");
  }
  return context;
}

export { store, useStore };

Store itself is almost always a class with multiple fields and methods. Let's say I define it with example methods:

export class Store {
  /** Here is some other code with constructor, methods, fields etc... */
  public doSomething() { return this.doSomthingElse() };
  private doSemothingElse() { console.log("done something else")};
}

Why is it that when I use my hook like this with destructuring: const { doSomething } = useStore(); I get can not read property doSomethingElse of undefined meaning this is undefined, that way. But when I do: const store = useStore(); store.doSomething(); It works just fine?



Solution 1:[1]

It works that way due to this behaviour in JS classes. Binding calling method to this inside a constructor solves the issue with undefined context within a hook.

this.doSomething = this.doSomething.bind(this);

Kudos to Gabriele Petrioli for giving explanation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jckmlczk