Writing good code in React JS is important to make sure your project runs smoothly and is easy to work with. Here are 5 easy tips to make your code cleaner and better!
- Avoid Writing Functions Directly in JSX Writing functions directly inside JSX can slow down your app. Instead, write the function outside and pass it to your component.
// Instead of this:
<button onClick={() => doSomething()} />
// Do this:
const handleClick = () => doSomething();
<button onClick={handleClick} />
Organize Your Files
Keep your files neat by creating folders for components, utilities, hooks, etc. This helps keep your project clean and easy to find what you need.Use Functional Components & Hooks
Instead of using class components, use functional components with hooks like useState and useEffect. They are easier to write and read.
// Example of a Functional Component
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
- Create Reusable Components Don't repeat yourself! Write components that can be reused by passing props to them. This saves time and makes your code cleaner.
const Button = ({ label, onClick }) => (
<button onClick={onClick}>{label}</button>
);
- Use PropTypes or TypeScript PropTypes or TypeScript help you make sure the data you pass to your components is correct, preventing bugs early on.
import PropTypes from 'prop-types';
const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;
Greeting.propTypes = {
name: PropTypes.string.isRequired,
};
Top comments (0)