๐ฅ๐ฒ๐ฎ๐ฐ๐.๐ท๐ ๐๐น๐ฒ๐ฎ๐ป ๐๐ผ๐ฑ๐ฒ ๐ฃ๐ฟ๐ฎ๐ฐ๐๐ถ๐ฐ๐ฎ๐น ๐จ๐๐ฒ
Write better React code with these six rules.
- Separate data from your view Keep your JSX clean. Do not mix data fetching with your UI. Move your logic into a custom hook. This makes your component easy to read and test.
- Bad: Fetching data inside the component.
- Good: Using a custom hook like useUser() to handle data.
- Manage form state efficiently Avoid creating a new useState for every single input field. This makes your code messy as your form grows.
- Bad: One useState per input.
- Good: One object to hold all form data.
- Better: Use a library like react-hook-form to handle inputs.
- Set default values for optional props When you use optional props, always provide a default value. This prevents bugs when a prop is undefined.
- Bad: Letting a prop stay undefined.
- Good: Setting a default value like isDisplayNone = false.
- Clean up your imports Organize your files so imports stay short and clean.
- Use an index.tsx file in your folders. This lets you import multiple components from one path.
- Use absolute paths. Avoid long paths like ../../../components. Use @components instead.
- Use built-in array methods Stop writing manual loops for simple tasks. Use standard JavaScript methods to keep your code readable.
- Use .includes() to check for a value.
- Use .some() to check if a condition exists.
- Use .filter() to remove items.
- Use .reduce() to calculate totals.
- Use constants for magic numbers Never use random numbers in your logic. If a status is 0, nobody knows what that means.
- Bad: if (status === 0)
- Good: Create a Status object. Use Status.Invalid instead. This makes your code tell a story.
Source: https://dev.to/kkr0423/reactjs-clean-code-practical-use-10kg