-
React/createContext, useContext 사용하기Language/React 2022. 10. 12. 16:56
Class Component -> createContext
const MyContext = React.createContext(); class MyComponent extends Component { const [user, setUser] = useState(null); render() { const propsMy = { ... isMobile: () => { return this.isMobile }, ... }; return ( <Router> <div className="app"> <MyContext.Provider value={this.props.propsMy}> <Topbar /> <Switch> <Route path="/login" exact component={Login} /> ... <Route path="/orders"> <Orders /> </Route> ... </Switch> <BottomBar /> </MyContext.Provider> </div> </Router> ); } }; export default MyComponent;
Class Component -> useContext
class UserComponent extends Component { static contextType = MyContext; state = {}; componentDidMount() { window.addEventListener('resize', this.resize.bind(this)); } resize() { if (this.context.isMobile() === true) { console.log('MOBILE'); } else { console.log('PC'); } } componentWillUnmount() { window.removeEventListener("resize", this.resize.bind(this)); } render() { return ( <> </> ); } } export default UserComponent;
Function -> createContext
const UserContext = React.createContext(null); const App = () => { const [user, setUser] = useState(null); return ( <Router> <div className="app"> <UserContext.Provider value={user}> <Topbar /> <Switch> <Route path="/login" exact component={Login} /> <Route path="/home" exact component={Home} /> <Route path="/" exact component={ShopMenu} /> <Route path="/orders"> <Orders /> </Route> <Route path="/wishlist" exact component={Wishlist} /> <Route path="/wallet" exact component={Wallet} /> <Route path="/cart" exact component={Cart} /> </Switch> <BottomBar /> </UserContext.Provider> </div> </Router> ); };
Function -> useContext
const Topbar = () => { const user = useContext(UserContext); // use `user` here };
참조)
https://stackoverflow.com/questions/69675357/react-what-is-the-proper-way-to-do-global-state
https://stackoverflow.com/questions/61498035/react-usecontext-inside-class
'Language > React' 카테고리의 다른 글
React/moment 사용 탐방 (0) 2022.10.21 React/memory leak - componentWillUnmount Event 제거 이슈 (0) 2022.10.19 React/AntV G2plot Chart 적용 (0) 2022.10.12 React/Swiper 적용 (0) 2022.10.12 React/Jwt 연동 (access token, refresh token) (0) 2022.08.10