The useReducer is a hook that provides a way to manage state in a React component.
Is it dependant on redux?
No, it's provided by React and can be used independently of Redux.
useReducer is a way to manage state within a single React component, whereas Redux is a state management library that is used to manage state in larger applications.
While useReducer and Redux share some similarities, they are not required to be used together. You can use useReducer on its own in a React component, or you can use Redux to manage state in an application that includes multiple components.
More on useReducers
It is similar to the useState hook, but it allows you to manage more complex state logic and handle multiple state updates with a reducer function.
To use useReducer, you first need to define a reducer function that takes in the current state and an action, and returns a new state.
Then, in your component, you can call useReducer and pass in the reducer and an initial state. This returns an array with the current state and a dispatch method, which you can use to trigger state updates by calling the dispatch method and passing in an action.
Here is an example of using useReducer in a React component:
import {useReducer}from 'react'
const initialState = {
count: 0,
};
/////takes in the current state and an action, and **returns a new state.**/updates state
const reducer = (state, action) => {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
};
function MyComponent() {
//call useReducer and pass in the reducer and an initial state
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "increment" })}>
Increment
</button>
<button onClick={() => dispatch({ type: "decrement" })}>
Decrement
</button>
</div>
);
}
In this example, the useReducer hook is called with the reducer function and the initialState object.
This returns the state object and a dispatch method, which is used to trigger state updates by calling dispatch and passing in an action object. The state object contains a count property that is incremented or decremented when the corresponding buttons are clicked.
Thanks for this article. So the useReducer hook is like useState but allowing a more complex setter functionality, right? Redux is a global state management and allows us to reuse a state in multiple components. If I have understood your article correctly, then useReducer is still a local state. In the above example, I do not see the benefit of using useReducer instead of useState. The dispatch logic could be easily implemented using a normal state and some sort of handleOnClick function that sets the state depending on the type parameter. The code would look almost identical. Where exactly is the benefit when not using redux?