Skip to content
This repository was archived by the owner on Jun 21, 2020. It is now read-only.

Commit db3b702

Browse files
Merge pull request #6 from magnusdahlstrand/master
Remove usage of `setState` on every frame
2 parents 59e540c + ad8f708 commit db3b702

File tree

1 file changed

+12
-22
lines changed

1 file changed

+12
-22
lines changed

src/AnimationFrameComponent.jsx

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,13 @@ module.exports = function AnimationFrameComponent(InnerComponent, throttleMs) {
1111
this.endAnimation = this.endAnimation.bind(this);
1212
this.startAnimation = this.startAnimation.bind(this);
1313

14-
this.state = {
15-
isActive: true,
16-
rafId: 0,
17-
lastInvocationMs: 0
18-
};
14+
this.isActive = true;
15+
this.rafId = 0;
16+
this.lastInvocationMs = 0;
1917
}
2018

2119
loop(time) {
22-
const { lastInvocationMs, isActive } = this.state;
20+
const { lastInvocationMs, isActive } = this;
2321
const isAnimatable = !!(this.innerComponent && this.innerComponent.onAnimationFrame);
2422

2523
// Latter const is defensive check for React Native unmount (issues/#3)
@@ -28,29 +26,23 @@ module.exports = function AnimationFrameComponent(InnerComponent, throttleMs) {
2826
const hasTimeElapsed = !throttleMs || time - lastInvocationMs >= throttleMs;
2927

3028
if (hasTimeElapsed) {
31-
this.setState({ lastInvocationMs: time });
29+
this.lastInvocationMs = time;
3230
this.innerComponent.onAnimationFrame(time, lastInvocationMs);
3331
}
3432

35-
this.setState({
36-
rafId: requestAnimationFrame(this.loop)
37-
});
33+
this.rafId = requestAnimationFrame(this.loop);
3834
}
3935

4036
endAnimation() {
41-
cancelAnimationFrame(this.state.rafId);
37+
cancelAnimationFrame(this.rafId);
4238

43-
this.setState({
44-
isActive: false
45-
});
39+
this.isActive = false;
4640
}
4741

4842
startAnimation() {
49-
if (!this.state.isActive) {
50-
this.setState({
51-
isActive: true,
52-
rafId: requestAnimationFrame(this.loop)
53-
});
43+
if (!this.isActive) {
44+
this.isActive = true;
45+
this.rafId = requestAnimationFrame(this.loop);
5446
}
5547
}
5648

@@ -59,9 +51,7 @@ module.exports = function AnimationFrameComponent(InnerComponent, throttleMs) {
5951
throw new Error('The component passed to AnimationFrameComponent does not implement onAnimationFrame');
6052
}
6153

62-
this.setState({
63-
rafId: requestAnimationFrame(this.loop)
64-
});
54+
this.rafId = requestAnimationFrame(this.loop);
6555
}
6656

6757
componentWillUnmount() {

0 commit comments

Comments
 (0)