- [CODE STYLE] - Don't use one-letter variable naming. (It could be confusing for another developer, who reads your code. Also, it would really hard to find this variable in the code editor using search)
BAD EXAMPLE:
onChange={(e) => setVariable(e.target.value)}
GOOD EXAMPLE:
onChange={(event) => setVariable(event.target.value)}
ALSO GOOD EXAMPLE:
onChange={(changeEvent) => setVariable(changeEvent.target.value)}
- [CODE STYLE] - Don't repeat yourself. If you see that you copy/paste some block code, maybe, it's time to create a separate variable/function
- [CODE KNOWLEDGE] - If you are using a non-mutating array method, you don't need to create a copy of the array
BAD EXAMPLE:
const filteredCats = [...cats].filter(cat => cat.age > 6);
GOOD EXAMPLE:
const filteredCats = cats.filter(cat => cat.age > 6);
- [REACT KNOWLEDGE] - Don't render the component if the property that you pass to the component has
null
orundefined
value.
BAD EXAMPLE:
const CatInfo: FC<Props> = (props) => {
const { cat } = props;
return (
{cat
? <p>{cat.name}</p>
: null
);
}
GOOD EXAMPLE:
const CatInfo: FC<Props> = (props) => {
const { cat } = props;
return (
<p>{cat.name}</p>
);
}
....
{cat
? <CatInfo cat={cat} />
: <p>No cat found</p>
}
- Prepare data in one place (App component) and pass it to child components. Don't use
import
keyword in non-root components
BAD EXAMPLE:
import owners from './owners';
const CatInfo: FC<Props> = (props) => {
const { cat } = props;
const { ownerId } = props;
const foundOwner = owners.find(owner => owner.id === ownerId);
return (
<>
<p>{cat.name}</p>
<p>{foundOwner.name}</p>
</>
);
}
GOOD EXAMPLE:
import owners from './owners';
const catWithOwner = {
...cat,
owner: owners.find(owner => owner.id === ownerId) || null
}
const App: FC = () => {
return (
{catWithOwner
? <CatInfo cat={catWithOwner} />
: <p>No cat was found</p>
}
)
}
import owners from './owners';
const CatInfo: FC<Props> = (props) => {
const { cat } = props;
const { owner, name } = props;
return (
<>
<p>{name}</p>
<p>{owner.name}</p>
</>
);
}
- [CODE KNOWLEDGE] - While handling form values, trigger submit logic using
onSubmit
prop of form, instead ofonClick
submit button
BAD EXAMPLE:
const AddCatForm: FC<Props> = (props) => {
const handleSubmit = () => {};
return (
<form>
<input type="text />
<button type="submit" onClick={handleSubmit}>
Add cat
</button>
</form>
);
}
GOOD EXAMPLE:
const AddCatForm: FC<Props> = (props) => {
const handleSubmit = () => {};
return (
<form onSubmit={handleSubmit}>
<input type="text />
<button type="submit">
Add cat
</button>
</form>
);
}