Redux만 사용하고 정작 ContextAPI를 사용해본적이 없어서 오늘은 ContextAPI에 대해서 알아보기 🤓
createContext
함수를 사용해서 ContextAPI를 생성한다.
Provider
는 Context에서 사용 할 값을 설정할 때 사용Consumer
는 나중에 우리가 설정한 값을 불러와야 할 때 사용// contexts/themeContext.js
import React, { createContext, useContext, useState } from "react";
const ThemeContext = createContext();
const ThemeUpdateContext = createContext();
// Custom Hooks
export const useColor = () => useContext(ThemeContext);
export const useUpdateColor = () => useContext(ThemeUpdateContext);
export const ThemeProvider = ({ children }) => {
const [isClicked, setIsClicked] = useState(false);
const handleClick = () => setIsClicked(!isClicked);
return (
<ThemeContext.Provider value={isClicked}>
<ThemeUpdateContext.Provider value={handleClick}>
{children}
</ThemeUpdateContext.Provider>
</ThemeContext.Provider>
);
};
// App.js
import Box from "./components/Box";
import Button from "./components/Button";
import { ThemeProvider } from "./contexts/themeContext";
const App = () => {
return (
<ThemeProvider>
<Box />
<Button />
</ThemeProvider>
);
};
export default App;
// Box.js
import styled from "styled-components";
import { useTheme } from "../contexts/themeContext";
const Wrapper = styled.div`
background-color: ${(props) => (props.isClicked ? "black" : "coral")};
// ...
`;
const Box = () => {
const colorTheme = useTheme();
return <Wrapper isClicked={colorTheme}>I am a Box</Wrapper>;
};
export default Box;
// Button.js
import styled from "styled-components";
import { useUpdateTheme } from "../contexts/themeContext";
const Wrapper = styled.button`
margin-top: 3rem;
`;
const Button = () => {
const handleClick = useUpdateTheme(); // (*)
return <Wrapper onClick={handleClick}>Click Me</Wrapper>;
};
export default Button;
value={[isClicked, setIsClicked]}
와 같이 내보낼수 있다.// themeContext.js
import React, { createContext, useContext, useState } from "react";
const ThemeContext = createContext();
// Custom Hooks
export const useTheme = () => useContext(ThemeContext);
export const ThemeProvider = ({ children }) => {
const [isClicked, setIsClicked] = useState(false);
return (
<ThemeContext.Provider value={[isClicked, setIsClicked]}>
{children}
</ThemeContext.Provider>
);
};
import styled from "styled-components";
import { useTheme } from "../contexts/themeContext";
const Wrapper = styled.button`
margin-top: 3rem;
`;
const Button = () => {
const [isClicked, setIsClicked] = useTheme(); // (*)
const handleClick = () => setIsClicked(!isClicked);
return <Wrapper onClick={handleClick}>Click Me</Wrapper>;
};
export default Button;
import styled from "styled-components";
import { useTheme } from "../contexts/themeContext";
const Wrapper = styled.div`
background-color: ${(props) => (props.isClicked ? "black" : "coral")};
// ...
`;
const Box = () => {
const [isClicked] = useTheme(); // (*)
return <Wrapper isClicked={isClicked}>I am a Box</Wrapper>;
};
export default Box;