1

With React Hooks, what is the best practice for storing a constant that requires significant computation to initialize but then doesn't change across re-renders?

Option 1: Constant Outside of Hook Definition

const x = heavyCalculation();
export default function MyHook() {
  return <div>x</div>
}

Option 2: useMemo

export default function MyHook() {
  const x = useMemo(() => heavyCalculation(), [])
  return <div>x</div>
}

Option 3: useRef

export default function MyHook() {
  const x = useRef(heavyCalculation())
  return <div>x</div>
}

I like Option 1, but I don't know if it's considered the best for hooks stylistically.

2

1 Answer 1

3

Option 1 works, but it's not particularly flexible - what if multiple instances were rendered at a given time, and they didn't all share the same heavyCalculation result? But if you can count on the value only having to be computed exactly once, across all components, go for it.

Option 2 is the right choice, but note that you can simplify it to:

export default function MyHook() {
  const x = useMemo(heavyCalculation, [])
  return <div>{x}</div>
}

(also note that you do need {x}, not just x, to show the x result)

Option 3 will not work, since heavyCalculation will be invoked on every render. (You'd also have to reference x.current, not just x)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.