Skip to content

feat: provide useLayoutEffect equivalent #3284

@marcincichocki

Description

@marcincichocki

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Feature: Want this? Upvote it!This PR or Issue may be a great consideration for a future idea.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions