Practice - ReactJs (Redux)
Practice - ReactJs (Redux)
const initialState = {
value: 0
};
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
- Implementation into react components
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from "../redux/slices/counterSlice";
function CounterComponent() {
const count = useSelector(state => state.counter.value);
const dispatch = useDispatch();
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={() => dispatch(increment())}>Increment</button>
<span>{count}</span>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
<div>
<input
type="number"
onChange={(e) => dispatch(incrementByAmount(parseInt(e.target.value) || 0))}
placeholder="Enter value"
/>
<button onClick={() => dispatch(incrementByAmount(5))}>Add 5</button>
</div>
</div>
);
}
export default CounterComponent;
useSelector
is used to select specific parts of the state from the Redux store within a React component. It
allows React components to subscribe to specific parts of the state and will re-render
whenever the related state changes.
useDispatch
is used to access the Redux dispatch function within a React component. This dispatch
function is used to send actions to the Redux store, which will cause state changes.
1. Redux AsyncThunk (for communication with API)
-Creating a User Slice(userSlice.js) and fetchUser with AsyncThunk in the
redux/slicer Folder
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
function UserComponent() {
const userData = useSelector((state) => state.user.data);
const isLoading = useSelector((state) => state.user.loading);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchUser());
}, [dispatch]);
if (isLoading) {
return <div>Loading...</div>;
}
console.log(userData);
return (
<div>
<h2>User Details</h2>
{userData?.map((item) => (
<div key={item.id}>
<span>Name: {item.name}</span>
<span> - </span>
<span>Email: {item.email}</span>
</div>
))}
</div>
);
}
export default UserComponent;
https://redux.js.org/tutorials/fundamentals/part-8-modern-redux
https://www.youtube.com/watch?v=u3KlatzB7GM&list=PL0Zuz27SZ-6M1J5I1w2-
uZx36Qp6qhjKo