Home > database >  Why I can not create a function that starts with "use" in a react project?
Why I can not create a function that starts with "use" in a react project?

Time:11-22

I am trying to run the code below but the react "compiler" does not complete its task and keeps showing this error message "React Hook "x" cannot be called at the top level".

  • I'm not using react hooks
  • I'm no even tryin to create a component
  • I just want to write a simple function
const map = (fn: (value: any, index: number, array: any[]) => unknown) => (xs: any[]) => xs.map(fn)
const pipe = (...fns: Function[]) => (x: any) => fns.reduce((res, fn) => fn(res), x)

const prices = [30,35,40,50,65,77,83,99.99]
const applyDiscoundAndFormat = (discount: number) => pipe(
  map((e: number) => (1 - discount / 100) * e),
  map((e: number) => e.toFixed(2))
)

const use20PercentCupom = applyDiscoundAndFormat(20)
console.log(use20PercentCupom(prices)) //this line keeps showing the error message

I know that if I rename this function it will work, but why the react project simply just treats every function that starts with "use" like a hook? Are there no other more efficient ways to do this?

CodePudding user response:

Hooks are special functions in react identified by name ("use" prefix). Hooks have some restrictions: https://reactjs.org/docs/hooks-rules.html

So if your function name starts with "use" it is identified as a hook so the restrictions apply.

CodePudding user response:

Use synonyms like "utilize" or "apply"

  • Related