=
useReducer
in React vs Vuex or Custom State Management
- React’s
useReducer
is a way to manage complex state logic in functional components. - In Vue, Vuex is typically used to manage complex or global state across components.
- Alternatively, you can use a custom function to manage state updates similar to
useReducer
.
Example in Vue: Using Vuex for centralized state management:
=
useReducer in React vs. Vuex or Custom State Management in Vue
React’s useReducer to manage complex state logic:
javascript
Copy code
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
Vue equivalent using Vuex:
javascript
Copy code
// Vuex store
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++; },
decrement(state) { state.count--; }
}
});
// In a Vue component
export default {
computed: {
count() { return this.$store.state.count; }
},
methods: {
increment() { this.$store.commit("increment"); }
}
}
=
No comments:
Post a Comment