Our examples are located under nodejs/next:
Solved ones:
The goal of this example is to understand when states and effects happen when changing between different routes that use the same component.
Behavior is follows:
This is likely because in React the state kept in the virtual DOM structure, and identical structure implies identical state. So when we change from post 1 to 2, we still have a Post object, and state is unchanged.
Next if we click:
then the count is back to 0. This is because we changed the Post object in the DOM to Index and back, which resets everything.
This example also illustrates how to prevent this from happening with useEffect.
This is a minimal reproducible example for the terrible problem of external effects applying twice to refs for effects that are not idempotent and thus blowup if applied twice.
The issue is currently discussed at: react.dev/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed (archive) which says "you need to cleanup the thing yourself". web.archive.org/web/20240720100401/https://react.dev/learn/synchronizing-with-effects#subscribing-to-events is also says that for the specific case of addEventListener.
But that's annoying! Can't we just somehow tell if we applied twice or not to avoid having to implement a cleanup? What if a third party system does not provide a cleanup at all?
Is the correct solution to just just have a useEffect with empty dependency list? Seems to be good according to posts and to ESLint!
Tried to do a React only reproduction at: react/ref-twice.html.
In this example we attempt to inject React elements into statically rendered HTML coming from the server, and properly hydrate them.

Articles by others on the same topic (0)

There are currently no matching articles.