My approach to building a React Project
Hosenur published this article 10/15/2023
2020 was when I started my web development journey, at first I used plain HTML and CSS, without the JavaScript part. I started writing JavaScript for the first time in a React Project a very few days after I found myself repeating HTML tags and CSS classes, I knew there was a better way to do it, so I did some searches and found React. Interning, building several personal projects with React and React Native since then , I have learnt several design principles , folder and code strucutre. In this article I will be sharing my approach to building a React Project.
Atomic Responsibility
Whether it is the smallest component, a hook a utility function, a component or a context every file needs to solve only and only a single problem. This helps in debugging a lot easier, you dont have to keep a watch of multiple things in a file , finding what changes when to fix a bug.
2 Drills at Max
If a prop needs to be passed two component deep , I consider it as a bad design and prefer putting it in a shared global store or use a custom hook, the code becomes messy accessing props from parent and then passing the sam prop to a children. In case if the prop is only used in a specific component in the whole project it becomes irrelevant to store the prop in a global store, I strucutre my components in such a way that it takes the least number of drills.
Simple fetch is boring
Axios is my go to library for making API calls, but simple Axios calls leave us with stale data until I make a refresh call, but all this is simplified as a cake walk with SWR.
Hooks
Lets take for example in a app , we are dealign with projects namely creating them , deleting them and updating them. Now two scenarios arise, one is when the projects are accessed in a single page in the whole app or accessed in multiple componensts.
In the fist case, I prefer usign a custom hook, let's take useProjects according to the atomic design principle, it will export all required functions to create, delete and update a project. Here is an example for the same.
import { useState } from 'react';
const useProjects = () => {
cosnt [projects, setProjects] = useState([]);
useEffect(()=>{
// fetch projects and setProjects
},[])
return {
projects
}
}
export default useProjects;