如果我在 useEffect 中调用多个 useStates,它们会被批处理还是会导致性能问题?
If i call multiple useStates in a useEffect will they be batched or they will lead to performance issues?
如果我在一个 useEffect 中调用多个 useState,它们会被批处理还是会导致性能问题?
示例:
useEffect(
() => {
setDate(date)
setStartDate(startDate)
setEndDate(endDate)
setSelectedNodes([])
setName('Test')
},
[dateChanged, startDate, endDate]
)
本质上没有错,但我发现 useReducer hook 使它更易于管理。
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'specialThing':
return {endDate: action.endDate, startDate: action.startDate, ...etc}
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
dispatch({ type: 'specialThing', startDate, endDate, ...etc })
}, [dateChanged, startDate, endDate])
return (
...
);
}
如果我在一个 useEffect 中调用多个 useState,它们会被批处理还是会导致性能问题?
示例:
useEffect(
() => {
setDate(date)
setStartDate(startDate)
setEndDate(endDate)
setSelectedNodes([])
setName('Test')
},
[dateChanged, startDate, endDate]
)
本质上没有错,但我发现 useReducer hook 使它更易于管理。
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'specialThing':
return {endDate: action.endDate, startDate: action.startDate, ...etc}
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
dispatch({ type: 'specialThing', startDate, endDate, ...etc })
}, [dateChanged, startDate, endDate])
return (
...
);
}