React Native

What is the purpose of the useReducer hook in React Native?

Medium
10
Added
The useReducer hook is used for managing more complex state logic that involves multiple sub-values or when the next state depends on the previous one.

Solution Code

React Native
-- Example Code --
import React, { useReducer } from "react";
import { View, Text, Button } from "react-native";

const initialState = { count: 0 };

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      return state;
  }
};

const App = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <View>
      <Text>Count: {state.count}</Text>
      <Button title="Increment" onPress={() => dispatch({ type: "increment" })} />
      <Button title="Decrement" onPress={() => dispatch({ type: "decrement" })} />
    </View>
  );
};

export default App;
Explanation
This code demonstrates how to use the useReducer hook to manage complex state logic.

Guided Hints

{'hint': 'Use useReducer for complex state management.'}
{'hint': 'Define a reducer function to handle state transitions.'}