stencil icon indicating copy to clipboard operation
stencil copied to clipboard

feat: provide useLayoutEffect equivalent

Open marcincichocki opened this issue 2 years ago • 2 comments

Prerequisites

Describe the Feature Request

Provide equivalent of react's useLayoutEffect so users can mutate DOM before it gets rendered. This will allow for example for calculating if node is overflowing.

Describe the Use Case

I want to update the template based on properties of a DOM node from that template. Because refs are set during render, I have to use either componentDidRender or componentDidLoad lifecycle hooks. In those hooks I can calculate whatever I need and mutate @State property that will trigger another render.

But this solution cause warning to appear in the console

The state/prop "<propName>" changed during "componentDidLoad()", this triggers extra re-renders, try to setup on "componentWillLoad()" 

and could cause flicker because of doubled render.

Describe Preferred Solution

Provide lifecycle hook, that could be used to mutate state before template gets painted.

Describe Alternatives

None

Related Code

@Component({
  tag: 'ref-example',
})
export class  RefExampleComponent {
  ref!: HTMLElement;

  @State() isOverflowing: boolean | null = null;

  render() {
    return (
      <Host>
        <div ref={el => this.ref = el as HTMLElement}></div>
        {isOverflowing ? 'overflow!' : 'no overflow!'}
      </Host>
    )
  }

  componentDidRender() {
    if (this.isOverflowing === null) {
      if (this.ref.scrollWidth > this.ref.offsetWidth) {
        this.isOverflowing = true;
      }
    }
  }
}

Additional Information

react's useLayoutEffect documentation: https://reactjs.org/docs/hooks-reference.html#uselayouteffect

marcincichocki avatar Mar 17 '22 10:03 marcincichocki

Thanks @marcincichocki! I've labeled this issue for folks to upvote with 👍's if this is something they'd be interested in seeing Stencil support

rwaskiewicz avatar Mar 17 '22 12:03 rwaskiewicz

Have you tried https://www.npmjs.com/package/@saasquatch/stencil-hooks ?

theo-staizen avatar May 27 '22 19:05 theo-staizen