Good practices in React

2 min read

Use an object for update multiple states

React state keeps track of the data which when changed triggers the React component to re-render. The more data you have to keep track of across your app.

const [state, setState] = useState({
  gender: "",
  name: "",
  age: 23
});

const onClick = () => {
  setState((prevState) => ({
    ...prevState,
    age: prevState.age + 1,
    name: "John",
    gender: 'male',
  }));
};

Avoid using indexes as key props

With keys, React can point which item has been changed, added, or removed from the array.

It is not recommended recommend using indexes for keys if the order of items may change.

const todoItems = todos.map((todo) =>
  <li key={todo.id}>
    {todo.text}
  </li>
);

https://reactjs.org/docs/lists-and-keys.html

Use object destructuring for props

It's cleaner and easy to read

const Button = ({text}) => {
  return <button>{text}</button>;
};

Use Object Literals

It's make our code more readable.

In this example we can't use ternary because there are more than two options and it's better to start using if's.

const {type} = animals

const components = {
  LION: AdminUser,
  CAT: EmployeeUser,
  DOG: NormalUser
};

const Component = components[type];

return <Component />;

Keep render as clean as possible

Minimum logic inside render components.

const getUsers = () => dispatch(ACTION_GET_USERS)

return (
  <button onClick={getUsers}>
    getUsers Button
  </button>
)

Use Template Literals

Try to avoid using string concatenation.

const animalDetails = `${animal.name} lives in ${animal.country} and eats ${animal.food}`

return (
  <div> {animalDetails} </div>
)

Conclusion

Congratulations if you've made it this far! I hope you learned a thing or two from this article.

I hope you have a wonderful day!