ReactJs Redux
Syntax
import { createStore } from 'redux';
const initState = {
count: 0
}
const reducer = (state = initState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
...state,
count: state.count + 1
}
case 'DECREMENT':
return {
...state,
count: state.count - 1
}
default:
return state
}
}
const store = createStore(reducer);
Example
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
export default function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
const increment = () => {
dispatch({ type: 'INCREMENT' });
};
const decrement = () => {
dispatch({ type: 'DECREMENT' });
};
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
Output
Counter: 0
* Increment Button
* Decrement Button
Explanation
Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. Redux was inspired by Flux, another application architecture for building reactive user interfaces.
Use
Redux is commonly used in react applications for state management. It allows for a centralized management of data and can greatly simplify the communication between components.
Important Points
- Redux is a predictable state container - it helps you manage application state in a predictable way.
- Redux is a tool that is used alongside React to manage application state more effectively.
- Redux stores all application state in a single location - the application store.
- Redux works by dispatching actions, which are handled by reducers.
- Reducers update the state in response to actions.
Summary
Redux is a powerful tool for managing application state in React applications. It provides a centralized location for storing data, which can greatly simplify communication between components. Redux works by dispatching actions that are handled by reducers, which update the state. By using Redux, you can create more predictable, reliable, and maintainable applications.