I'm listening to a websocket which triggers a callback once per second:
setState1 happens every second, setState2 also happens every second after 10 seconds and allows LargeChildComponent to display.
I found that updating this state was taking over 200ms.
const myWebsocketCallback = async(newData) => {
dataRef.current = [...dataRef.current, newData]
const start = performance.now()
setDataState(dataRef.current)
console.log('setState', performance.now() - start)
doWorkWithNewData()
}
So setting state was slow initially, and is extra slow when LargeChildComponent is rendering.
I found that moving a large JSON object from a state initialization to a init useEffect() reduced that time greatly.
- const [myBigData, setMyBigData] = useState(VERY_LARGE_JSON_OBJECT)
+ const [myBigData, setMyBigData] = useState()
+ useEffect(() => {
+ setMyBigData(VERY_LARGE_JSON_OBJECT)
+ }, [])
Is default state value checked every render? Should I be initializing state in a useEffect(myFunc, [])?
The above change alone made a MASSIVE improvement.
However, that setState() is still taking 80ms+, AND it seems to be dependent on the size of the render (child components).
I was under the impression that setState() is an async task and should happen quickly regardless of any components which depend on it.
Why is it still taking 80ms to update state?
Is it due to being inside a callback function? Does state actually wait for children to render?

