Frontend Development: Wrapper vs. Container

Peter Jeon·2023년 6월 27일
0

Frontend Development

목록 보기
29/80
post-custom-banner

Wrapper vs Container

In the world of frontend development, especially when dealing with React, two terms often cause confusion: wrapper and container. Both have different roles, and understanding these differences is crucial for effective component composition. In this article, we will look at these two elements, compare them, and provide some examples to illustrate their usage.

WrapperContainer
DefinitionA component that encapsulates other components for styling or layout purposes.A component connected to the application's state (Redux or any state management). It gets and sets the state and passes down props to its children.
UsageLayout, styling, and reusability.Data fetching, state management.
Child ComponentsChild components receive props, but mostly for UI rendering.Child components can receive functions and state as props.

What is a Wrapper Component?

Wrapper Component

A wrapper component in React is a component that wraps and augments other components. It's typically used for code reuse and component abstraction for styling purposes.

function WrapperComponent({ children }) {
  return <div className="wrapper-style">{children}</div>;
}

In the above code, WrapperComponent is a wrapper component that wraps the children prop inside a div with a class of wrapper-style. This component can now be reused across the application to provide consistent styling.

What is a Container Component?

A container component, on the other hand, is concerned with how things work. It usually defines the data that a component needs and how to get and transform that data. Container components are often generated using higher-order functions, like connect from React Redux.

import { connect } from 'react-redux';

function ContainerComponent({ data, fetchData }) {
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return <div>{data}</div>;
}

const mapStateToProps = state => ({
  data: state.data,
});

const mapDispatchToProps = dispatch => ({
  fetchData: () => dispatch(fetchDataAction()),
});

export default connect(mapStateToProps, mapDispatchToProps)(ContainerComponent);

Here, ContainerComponent is a container component that is connected to the Redux store. It fetches data when the component mounts and displays this data.

Conclusion

To conclude, while wrapper and container components might seem similar, they have different roles in a React application. A wrapper is more about presentational concerns — layout, style, and UI consistency — while a container is more about logic and state management, providing data and behavior to UI or other container components. Understanding the difference and proper usage of these components can lead to more maintainable code.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글