With Redux, we can use it to store data in a central location in our JavaScript app. It can work alone and it’s also a popular state management solution for React apps when combined with React-Redux.
useSelector():
useSelector()
hook will fetch data from store, in redux.
useSelector
is a function that takes the current state as an argument and returns whatever data you want from it and it allows you to store the return values inside a variable within the scope of you functional components instead of passing down as props.
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { updateFirstName } from "../redux/actions";
const Form = () => {
const dispatch = useDispatch();
const nameObj = useSelector((state) => state.nameReducer);
const { firstName } = nameObj;
const handleFirstName = () => {
dispatch(updateFirstName("Jason"));
};
return (
<React.Fragment>
<div className="container">
<label>First Name : {firstName}</label>
<button onClick={handleFirstName}>Update First Name</button>
<label>Last Name : {lastName}</label>
<button type="submit" onClick={handleLastName}>
Update First Name
</button>
</div>
</React.Fragment>
);
};
export default Form;
useStore():
useStore()
hook returns a reference to the same Redux store that was passed into Provider
component. This hook should probably not be used frequently. Prefer useSelector() as your primary choice. However, this may be useful for less common scenarios that do require access to the store, such as replacing reducers.
import React from 'react'
import { useStore } from 'react-redux'
export const ExampleComponent = ({ value }) => {
const store = useStore()
// EXAMPLE ONLY! Do not do this in a real app.
// The component will not automatically update if the store state changes
return <div>{store.getState().obj.name}</div>
}
useDispatch():
useDispatch()
hook is equivalent of mapDispatchToProps
.
We will invoke useDispatch
and store it to a variable, dispatch
. This hook returns a reference
to the dispatch function
from the Redux store. You may use it to dispatch actions as needed. And we dispatch it by calling dispatch passing in the return value from the action creator.
import React from "react";
//import useDispatch from react-redux
import { useDispatch} from "react-redux";
//these are actions define in redux>actions folder
import { updateFirstName } from "../redux/actions";
const Form = () => {
const dispatch = useDispatch();
const handleFirstName = () => {
//dispatching the action
dispatch(updateFirstName("Jason"));
};
return (
<React.Fragment>
<div className="container">
<button onClick={handleFirstName}>Update First
Name</button>
</div>
</React.Fragment>
);
};
export default Form;