DEV Community

Raunak Sharma
Raunak Sharma

Posted on

5 Simple Ways to Improve Your React JS Code

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!

  1. 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} />

Enter fullscreen mode Exit fullscreen mode
  1. 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.

  2. 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>
  );
};

Enter fullscreen mode Exit fullscreen mode
  1. 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>
);

Enter fullscreen mode Exit fullscreen mode
  1. 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,
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)