0
How can I use hooks instead of redux in react?
4 Antworten
+ 1
Context API is a good option when we do not have frequency updates..but I need to use it somewhere which will update most of the time.
+ 1
Use MobX it has hooks implementation
0
You can use context API
0
useReducer is a hook in React that allows you to manage state in a function component using a reducer function. A reducer function is a function that takes the current state and an action, and returns the new state.
Here's an example of using useReducer to manage a simple counter state in a React component:
import React, { useReducer } from 'react';
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:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}