Redux_Notes
Redux_Notes
React Redux is a library that provides bindings to connect React components with
the Redux state management library. Redux is a predictable state container for
JavaScript apps, and it helps manage the state of your application in a predictable
way. React Redux provides a way to access the Redux store and dispatch actions from
your React components.
Key Concepts
Redux Store: The single source of truth that holds the state of your entire
application.
Actions: Plain JavaScript objects that describe an event that has occurred in the
application. Actions typically have a type field that indicates the type of action
and an optional payload field containing additional information.
Reducers: Pure functions that take the current state and an action as arguments and
return a new state. Reducers specify how the application's state changes in
response to actions sent to the store.
Provider: A higher-order component from React Redux that makes the Redux store
available to your React components.
Connect: A function from React Redux that connects React components to the Redux
store. It allows components to access the state and dispatch actions.
Dependencies:
store.js
--------
// src/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
Counter Slice:
A slice is a collection of Redux reducer logic and actions for a single feature of
your app.
// src/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
index.js
-------
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
counter.js
// src/Counter.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from './counterSlice';
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
<button onClick={() => dispatch(incrementByAmount(5))}>Increment by
5</button>
</div>
);
};
export default Counter;
App.js
// src/App.js
import React from 'react';
import Counter from './Counter';