Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant ES6 way to update state in React

The syntax to update state in React has change a lot. I'm trying to find the most simple and elegant way to initiate and update it.

Got this RN code:

const { quotes } = require('./quotes.json')

class QuoteScreen extends Component {
  state = {
    QuoteIndex: 0
  }
  render() {
    return (
      <Image ...>
        <View ...>
          ...
          <ButtonNextQuote
            onPress={() => {
              this.setState((prevState, props) => {
                return {
                  QuoteIndex: (prevState.QuoteIndex + 1) % (quotes.length - 1)
                }
              })
            }}
          />
        </View>
      </Image>
    )
  }
}

Would it be possible to reduce the updating of state in the onPress?

Would like to avoid calling an anonymous function twice but don't want to reference and bind a handler. Would also like to avoid using the return..

like image 1000
Norfeldt Avatar asked Jun 10 '17 20:06

Norfeldt


People also ask

What is the proper way to update the state in React?

To update our state, we use this. setState() and pass in an object. This object will get merged with the current state.

How do I instantly update state in React JS?

To update state in React components, we'll use either the this. setState function or the updater function returned by the React. useState() Hook in class and function components, respectively.

What is the best method to update state in component?

setState method allows to change of the state of the component directly using JavaScript object where keys are the name of the state and values are the updated value of that state. Often we update the state of the component based on its previous state.

Can we directly update the state in React?

One should never update the state directly because of the following reasons: If you update it directly, calling the setState() afterward may just replace the update you made. When you directly update the state, it does not change this.


1 Answers

I would store the update function in a variable outside the class, e.g.

const newState = ({QuoteIndex: i}) => ({QuoteIndex: (i + 1) % nQuotes});

(of course you can chose to define the function in any way you like, maybe "terseness" isn't as important to you anymore if it isn't inlined)

And then you can just call this.setState(newState):

onPress={() => this.setState(newState)}
like image 182
Felix Kling Avatar answered Sep 28 '22 08:09

Felix Kling