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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay