Preact: Trash a component by key

Created on 7 Dec 2018  路  6Comments  路  Source: preactjs/preact

My question is quite simple, regarding this @sophiebits answer about React (https://stackoverflow.com/questions/21749798/how-can-i-reset-a-react-component-including-all-transitively-reachable-state), does Preact completly trash a component if the key props changes ?

Two bonus question :

  • does it reinit the real DOM during this process ?
  • if it does not, how to reset completely the component ?

My use case is that i render a preact (private) library component which i cannot touch, this component contains an html <video> element.
In my top level component, i'm trying to change the key on "reset" to destroy the element, and rebuild it from scratch.
Expected behaviour :
By so, i hope the <video> to reset it's behaviour, and display the first frame as a preview, in a fresh video ready to play from start.
Observed behaviour :
The video actually keep it's playing position between re-render, even with a different key

question

All 6 comments

Preact 8.x still has component recycling enabled, so changing keys will unmount the component and destroy its backing instance, but the DOM will be cached and then reused when the newly-keyed equal component is rendered in its place.

This is changing in the next version. key changes on components will trigger complete destruction and recreation of the corresponding DOM.

For your section part, you can use this workaround to completely disable DOM recycling for a given component, which will create its DOM representation fresh any time it is mounted:
https://gist.github.com/developit/fa084f3cb38778f93d58607377f416a3

I see, thanks for your answer, that's what i experienced, i will check your piece of code and give feedback for googlers.

Thanks for your feedback anyway.

FWIW, that workaround doesn't seem to work for me. I have:

function clearBase(component) {
  component.nextBase = component.__b = null;
}

and in a component class:

  componentWillUnmount() {
    Promise.resolve(this).then(clearBase);
  }

I confirmed with a console.log that clearBase is being called.

But the DOM is still being recycled. When I re-render the component at a later time, the DOM "flickers".

@aaronshaf hmm - flickering, unless its of images or videos, doesn't usually mean a recycling issue. Recycling tends to cause the opposite - it'll avoid flickering when it would otherwise have been expected. Is it possible something else is going on?

I think I have it figured out. I forget what I did to fix it. Sorry.

The recycler is gone with Preact X 馃帀

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rajaraodv picture rajaraodv  路  3Comments

skaraman picture skaraman  路  3Comments

adriaanwm picture adriaanwm  路  3Comments

kay-is picture kay-is  路  3Comments

KnisterPeter picture KnisterPeter  路  3Comments