어디서든 필요하면 state를 가져다 쓸 수 있다.
prop로 넘길 필요가 없다.
import { useDispatch, useSelector } from "react-redux/es/exports";
import "./App.css";
import Box from "./component/Box";
function App() {
let count = useSelector((state) => state.count);
const dispatch = useDispatch();
const minus = () => {
if (count !== 0) {
dispatch({ type: "MINUS" });
} else {
count = 0;
}
};
const plus = () => {
dispatch({ type: "PLUS" });
};
return (
<div>
<h1>{count}</h1>
<button onClick={minus}>-1</button>
<button onClick={plus}>+1</button>
<Box />
</div>
);
}
export default App;
import React from "react";
import { useSelector } from "react-redux/es/hooks/useSelector";
import GrandSonBox from "./GrandSonBox";
const Box = () => {
let count = useSelector((state) => state.count);
return (
<div>
this is box {count} <GrandSonBox />
</div>
);
};
export default Box;
import React from "react";
import { useSelector } from "react-redux/es/hooks/useSelector";
const GrandSonBox = () => {
let count = useSelector((state) => state.count);
return <div>this is GrnadSonBox {count}</div>;
};
export default GrandSonBox;