Mojang / ore-ui

💎 Building blocks to construct game UIs using web tech.
https://react-facet.mojang.com/
MIT License
404 stars 19 forks source link

RFC: meta information on which facet triggered re-run of hook #109

Closed Shenato closed 1 year ago

Shenato commented 1 year ago

The Problem

In some scenarios you need to keep track of more than one facet in one hook like useFacetEffect(), however the downside is you never really know which one of them triggered the current run of the effect, one option is is to split the effect, but sometimes that's not feasible depending on if the logic actually depends on more than one facet at the same time and they're not unrelated.

Proposed API change

The hook could accept a callback function overload whereby if the callback function has one more parameter than the facets passed to the hook it would keep track of the values and give you a perhaps meta object (name pending) with simple booleans for the facet's position in the dependency array which indicate which facet changed this run.

This should be an opt-in approach (by expecting an extra parameter in a X facet dependency hook), so we don't have to pay that cost in normal scenarios which are the abundant use-case for those hooks.

Example code below of how it can be used:

    useFacetEffect(
        (firstFacetValue, secondFacetValue, meta) => {
                if(meta.changed[0]) {
                   // Do something if firstFacetValue is the facet that changed triggering this effect
                }

                    if(meta.changed[1]) {
                   // Do something if secondFacetValue is the facet that changed triggering this effect
                }
        },
        [],
        [firstFacet, secondFacet],
    )
pirelenito commented 1 year ago

Closing this in favor of #122 . Feel free to re-open if that solution is not suficient.