DEV Community

Compute values on component mount with React Hooks: State vs Ref

Raicuparta on August 27, 2019

I recently came across this question: I have a functional React component that computes a value when the component is mounted. After mounting, th...
Collapse
 
maddes profile image
Daniel Scholtus

One extra improvement, move computevalue() definition outside of the function component to avoid re-defining the function on each cycle.

Collapse
 
raicuparta profile image
Raicuparta

Good point, the idea was always that computeValue() was something imported from somewhere else but I didn't make that clear in my minimal examples. I will update it.

Thanks!

Collapse
 
fnky profile image
Christian Petersen

Using setValue, as mentioned in the article, will force the component to update, which is undesirable in this case. The solution is to pass a function to the first argument of useState:

const [value] = useState(() => computeValue());

This will be initialized when component is mounted and the value will be available before rendering without forcing the component to update.

Collapse
 
raicuparta profile image
Raicuparta

I already mentioned that solution in the article. My solution will do an extra render, yes. But that's a good thing here, because the component won't be blocked from rendering while the value is being computed.