React Pattern

React Pattern

A react pattern named Container/View is followed to achieve clean and readable code.

Container/View Pattern

What is a pattern in react?

A pattern is defined as the way to write a code like there can be many ways to write react code, on the UI side it won't make any difference, but in the code level, it will matter because if we will not follow the best practices to write a code, then it won't be easy to maintain a huge codebase. So, following proper patterns whether dealing with a large or a small codebase, is a must.

What is a container/view pattern?

The ultimate goal of writing code following this pattern is to achieve clean, readable and robust code. Basically, Container means to write all your logic in one file and View means all HTML type stuff in another file. So, inorder to write the whole component in just one file, we will break that into several files, below is the folder structure...

image.png

So, let's first talk about the utils folder, there is in the file, named context.js, inside that we will set up the context API for the state management for that particular component to avoid prop drilling.

file - /utils/context.js

import React from "react";

export const SampleContext = React.createContext(null);

export const useSampleContext = () => {
  const context = React.useContext(SampleContext);
  if (!context)
    throw new Error("useSampleContext can not be used outside it's provider");
  return context;
};

Here we have a Sample component, and in level 1, we have index, container and view file. So, in the container file, we will write all our js logic, API calls, hooks implementation, and in the view file the main Html content is written.

file - /Sample.container.js

import React from "react";
import SampleView from "./Sample.view";
import { SampleContext } from "./utils/context";

export default function SampleContainer() {
  const [count, setCount] = React.useState(1);
  return (
    <SampleContext.Provider
      value={{
        count: count,
      }}
    >
      <SampleView />
    </SampleContext.Provider>
  );
}

file - /Sample.view.js

import React from "react";
import { useSampleContext } from "./utils/context";

export default function SampleView() {
  const { count } = useSampleContext();
  return <p>Count is {count}</p>;
}

And in the index file, we are exporting our main file, which is a container file.

file - index.js

export { default as Sample } from "./Sample.container";

So, you might be thinking of like how to import this component, let me show how...

import React from 'react'
import { Sample } from './Sample'

export default function App(){
  return(
    <Sample/>
  )
}

Conclusion

To make components reusable easily, debugging becomes faster and the readability increases. So, we should follow patterns, be it any.