React Native slider is having lagging issue
Asked Answered
B

4

6

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.

Bookkeeper answered 21/6, 2019 at 17:8 Comment(2)
you can use reduxDeckhand
it not working i triedBookkeeper
F
12

Try this solution, you reduce the number of updates :

onValueChange={value => {
  clearTimeout(this.sliderTimeoutId)
  this.sliderTimeoutId = setTimeout(() => {
    this.setState({value})
  }, 100)
}}
Fervid answered 29/6, 2019 at 15:9 Comment(1)
You can even play with the timerPushkin
A
2

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>
  );
}
Amboina answered 25/4, 2021 at 7:13 Comment(0)
B
1
<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.

Bordelaise answered 24/8, 2020 at 19:32 Comment(0)
Q
0

Just replace onValueChange in onSlidingComplete

Queenqueena answered 12/11, 2022 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.