DEV Community

Md Yusuf
Md Yusuf

Posted on

Understanding React's Built-in State Management

React's built-in state management relies on the useState and useReducer hooks to manage state within components. Here's a breakdown:

  1. useState:

    • This hook is used for managing local component state. It returns an array with two elements: the current state value and a function to update it.
    • Example:
     const [count, setCount] = useState(0);
    
     // Update state
     setCount(count + 1);
    
  2. useReducer:

    • For more complex state logic, useReducer is used. It works similarly to Redux by taking in a reducer function and an initial state, and returning the current state and a dispatch function.
    • Example:
     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 actions
     dispatch({ type: 'increment' });
    

These hooks help manage state locally within components without the need for external libraries.

Top comments (0)