Component - useReducer hook
This component uses the useReducer hook to manage state in a simple counter app. It shows how to update state based on actions, similar to how a cashier counts money by adding or subtracting bills.
This component uses the useReducer hook to manage state in a simple counter app. It shows how to update state based on actions, similar to how a cashier counts money by adding or subtracting bills.
View ├─ Text (shows count) └─ View (buttons container) ├─ Button (Increment) └─ Button (Decrement)
useReducer hook in React Native?useReducer is designed to handle complex state changes by using a reducer function and dispatching actions.useReducer.useReducer in a React Native component?useReducer returns an array with two elements: current state and dispatch function.const [state, dispatch] is correct.state.count after dispatching { type: 'increment' }?
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'increment' });useReducer setup:
const initialState = { count: 0 };
function reducer(state, action) {
if (action.type === 'increment') {
state.count += 1;
return state;
}
return state;
}
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'increment' });state.count directly, which is not recommended in React.isVisible state using useReducer. Which reducer function correctly toggles the state when dispatching { type: 'toggle' }?isVisible toggled using !state.isVisible.Pass the test and this pattern moves unknown