Is it a good coding practice to use a React state to be set once with the expectation it will never change to prevent re-renders?

Is it a good coding practice to use a React state to be set once with the expectation it will never change to prevent re-renders?

This may be a simple question but in our UI app we have a pattern my team has used to wrap an object of translation strings from i18next into a state which is never updated. The idea is, the translation function is used to generate the translations once and set into a state that is never updated, thus, when page re-renders for other reasons, it never re-calls the functions.

  const [translations] = useState({
    header: translate('translation.string.goes.here')
    welcomeMessage: translate('translation.string.goes.here')
  });

so then we can do something like translations.header and if page re-renders, the translate method isnt called anymore and basically, in a sense, caching the translations.

  1. Is this working as the expected result mentioned above? or is this way off what useState is?
  2. is this good or bad practice for this pattern in React?

Answer

when page re-renders for other reasons, it never re-calls the functions.

You are wrong it does re-call them just the result is discarded. Here is explanation on that.

If you really want it to be called once you could pass a initializer function to useState but it should be pure - which in your case it seems it is not.

So if you really want to avoid calls to translate on every re-render, maybe you can just store them in a variable declared outside your component - or store in ref using such approach:

function Video() {
  const playerRef = useRef(null);
  if (playerRef.current === null) {
    playerRef.current = new VideoPlayer();
  }
...

This pattern is allowed based on the docs:

Normally, writing or reading ref.current during render is not allowed. However, it’s fine in this case because the result is always the same, and the condition only executes during initialization so it’s fully predictable.

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions