Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!