Answer the question
In order to leave comments, you need to log in
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>
)
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question