TLDR; I would have used a simple constant.
const state = 'some state';
In general, I use this rules:
- If you'll need both
value
and setter
, then useState
hook is fine.
const [state, setState] = useState('Initial value');
- If you won't need to use setter, then use a
constant
instead. It will be recalculated in every render.
const state = 'Initial value';
- If you have a constant but initialisation is expensive, then consider using
useMemo(...)
hook. Dependencies array will allow you to have some control on when your calculations will be executed. Leave the array empty for a single calculation.
const state = useMemo(() => expensiveCalculations(), [deps]);
Don't abuse useMemo(...)
. Use it for optimisation when it makes
sense.
The case in the question is (for me) a good example of when useMemo(...)
is might not be the best choice. Mind that useMemo(...)
is not a "cost 0" operation and the optimisation mechanics could make the whole thing more expensive at the end. It depends on the context.