Reputation: 460
React Native slider onValueChange calling setState makes slider lag.
I also tried debounce function but it not solve my problem as I have to show the change value to the screen. hence without using debounce from lodash the slider is laggy and when use debounce the slider movement a bit smooth than previous method but the change in value(state value which I have to show on screen) is not instantaneously changing, change in value reflecting on screen is laggy means it taking time to show on screen.
import React from "react";
import Slider from "react-native-slider";
import { StyleSheet, View, Text } from "react-native";
export default class SliderExample extends React.Component {
state = {
value: 0.2
};
render() {
return (
<View style={styles.container}>
<Slider
value={this.state.value}
onValueChange={value => {
this.setState({ value })
// this.props.changeState(this.state.value)
console.log(this.state.value)
}}
maximumValue={100}
step={1}
/>
<Text>
Value: {this.state.value}
</Text>
</View>
);
}
}
Also one thing is that when I only implement this above slider then there is no problem but when I use it in full code where there are many states then its creates problem.
Upvotes: 6
Views: 6117
Reputation: 895
<Slider
value={0} //don't set value to this.state.value
onValueChange={value => this.setState({ value }) }
maximumValue={100}
step={1}
/>
The value prop should be state less. On assigning a state to the value prop when we trigger the onChangeValue prop, the value is set to previous state which makes it lag a bit when triggering onChangeValue. Value prop should only be provided a static number for initial reference.
Upvotes: 1
Reputation: 662
I solve this issue by creating a different state between the value and the preview value, like this:
const [value, setValue] = useState(0.2)
const [previewValue, setPreviewValue] = useState(0.2)
render() {
return (
<View>
<Slider
value={value}
onValueChange={value => setPreviewValue(value)}
onSlidingComplete={value => setValue(value)}
/>
<Text>
Value: {previewValue}
</Text>
</View>
);
}
Upvotes: 2
Reputation: 1556
Try this solution, you reduce the number of updates :
onValueChange={value => {
clearTimeout(this.sliderTimeoutId)
this.sliderTimeoutId = setTimeout(() => {
this.setState({value})
}, 100)
}}
Upvotes: 12