How to make one instead of multiple render calls?

  • 0
    There is a function where several different setState (setState1, setState2, setState3) are called and the component is rendered three times. Why doesn't React optimize the three setState calls? If I'm not mistaken, it says in the dock that React will optimize multiple calls to setState. Or does it only work when it refers to the same state and not different?
    Here is the code:
    const initialState = { text: [], answer: [] }
    const reducer = (textarea, action) => {
      switch (action.type) {
        case 'write':
          return { text: action.text, answer: [] }
        case 'clear':
          return { text: textarea.text, answer: [] }
        default:
          console.log('error')
      }
    }
    const App = () => {
    const [img, setImg] = useState({ state: 0 })
    const [textarea, dispatch] = useReducer(reducer, initialState)
    const record = () => {
              dispatch({ type: 'write', text: [] })
              dispatch({ type: 'clear' })
              setImg(prev => ({
                  ...prev,
                  state: 1,
                })
              })
    }
    return (
    <button onClick={record}>Click</button>
    )
    }

    I posted only a small part of the code, as it seems to me, the most necessary. If that's not enough, I can post most of the project.
    React Anonymous, May 25, 2019

  • 1 Answers
  • 0
    Or does it only work when it refers to one state and not different ones?




    Yes exactly
    Grace Allen

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!