ReasonJun

React : context (state management) 본문

Frontend/React

React : context (state management)

ReasonJun 2023. 8. 11. 01:02
728x90

React Context is a way to share data between components without having to pass props down manually at every level. This can be useful for sharing data that is used by many components in an application, such as the current user, the current theme, or the current location.

 

To use React Context, you first need to create a context object using the createContext() function. This function takes two arguments: the name of the context and a default value for the context. The name of the context is used to identify the context in your application, and the default value is the value that will be used for the context if there is no Provider for the context in the component tree.

 

Once you have created a context object, you can use it to create Provider and Consumer components. The Provider component is used to provide the context value to its children. The Consumer component is used to consume the context value from its parent.

 

The Provider component takes two props: the context object and the value prop. The value prop is the value that will be used for the context. The Consumer component takes one prop: the context name. The context name is used to identify the context that the Consumer component wants to consume.

 

The following code shows how to use React Context to share the current user between components:

const UserContext = createContext();

const UserProvider = ({ user }) => {
  return (
    <Provider value={user}>
      {children}
    </Provider>
  );
};

const UserConsumer = ({ children }) => {
  const user = useContext(UserContext);
  return (
    <div>
      {user && <h1>Hello, {user.name}</h1>}
      {children}
    </div>
  );
};

const App = () => {
  const user = { name: "John Doe" };
  return (
    <UserProvider value={user}>
      <UserConsumer>
        <h1>This is the App component</h1>
      </UserConsumer>
    </UserProvider>
  );
};

export default App;

In this code, the UserContext context object is created to store the current user. The UserProvider component is used to provide the current user to its children. The UserConsumer component is used to consume the current user from its parent. The App component uses the UserProvider component to provide the current user to all of its children. The UserConsumer component is used to display the current user's name in the App component.

 

React Context is a powerful tool that can be used to share data between components in a React application. It is especially useful for sharing data that is used by many components in an application.

728x90
Comments