react-piano icon indicating copy to clipboard operation
react-piano copied to clipboard

The component re-renders on each update.

Open ritz078 opened this issue 6 years ago • 7 comments

There should be a check for equality. PureComponent might not be a good fix as it uses shallowCompare and that will always return true even if playNotes has the same values but different reference. So we need to manually use shouldComponentUpdate.

ritz078 avatar Sep 18 '18 14:09 ritz078

You can make a small PureComponent wrapper around it to make it a pure component, and add any other checks you need for props. I've had to do this for other libraries so that's my solution here.

Passing a callback like playNote should hold the same reference in your code, if possible. The library can not determine that it is the same anonymous function created each time, no matter what checks it does.

So if there is a fix here, I would say thatPiano should be made into a PureComponent, and the user of the component is responsible for keeping their props the same each time. React already relies heavily on shallow compare, so it should feel natural.

mickmister avatar Nov 05 '18 02:11 mickmister

Can anyone provide an example as to how one can work around this problem? I tried to make a PureComponent wrapper, but without success.

finngl avatar Jun 16 '19 19:06 finngl

@finngl Ya I was totally wrong about what I said above. Making a wrapper doesn't solve the issue. The component in the library needs to be made into a PureComponent, then the userland code just needs to be responsible for consistent references for props.

I've also seen a ControlledPiano in the repo. I'm mobile right now so can't examine that but it may do what you need.

EDIT: I am working on a project with this library today so I can see if a PR can solve this, unless you'd be interested in submitting one @finngl

mickmister avatar Jun 16 '19 19:06 mickmister

@mickmister Thanks for the response. A PR would be much appreciated. I haven't had time to dive into the code myself.

finngl avatar Jun 17 '19 07:06 finngl

@mickmister My problem is solved! It turned out that it was a very trivial bug in my own code that caused my problem - it was not related to this issue at all.

finngl avatar Jun 18 '19 10:06 finngl

PRs are welcome. Sorry about the delay here, but I'm planning to look into this soon as well - I always wanted to make the component a PureComponent, but when I tried it I'd run into edge cases where the component would no longer re-render correctly, so it may take some investigation and involve API changes as well.

kevinsqi avatar Jun 18 '19 17:06 kevinsqi

I created on my own. Hopefully, it can help https://github.com/ritz078/raaga/blob/master/components/Piano.tsx

ritz078 avatar Jun 19 '19 08:06 ritz078