N
N
n1ksON2020-11-19 13:05:45
React
n1ksON, 2020-11-19 13:05:45

How to make one call instead of several render calls?

There is a function where several different setStates are called (setState1, setState2, setState3) and the component is rendered three times. Why doesn't React optimize three setState calls? If I'm not mistaken, the doc says that React will optimize multiple setState calls. Or does it only work when it applies to the same state and not to different ones?
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 this is not enough, I can lay out most of the project.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2020-11-19
@n1ksON

Or does it only work when it applies to the same state and not to different ones?

Yes exactly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question