Skip to content

Instantly share code, notes, and snippets.

@arnoldc
Last active August 1, 2023 14:25
Show Gist options
  • Save arnoldc/e99de826e0d0ad2a36d5663b1eb04128 to your computer and use it in GitHub Desktop.
Save arnoldc/e99de826e0d0ad2a36d5663b1eb04128 to your computer and use it in GitHub Desktop.
[React] Noob mistakes
/*
*
* ──────────── Table of contents ────────────
*
* @1.0 - Invoking Component Functions Directly
* @2.0 - Rule of hooks
* @3.0 - Conditional Rendering
* ──────────── Table of contents ────────────
*/
// @1.0 - Invoking Component Functions Directly
const EmailField = (props: any) => {
const [email, setEmail] = useState(props.email);
return (
<div>
<input type="text" name="email" />
</div>
);
}
function App() {
const emailField = EmailField({ email: ''});
return (
<div>
{/* this is wrong */}
{emailField}
{/* this is correct */}
<EmailField />
</div>
);
}
/******
if not done correctly:
rendered tree
App
if done correctly:
rendered tree
App
EmailField
********/
// @2.0 - Rule of hooks
const EmailField = (props: any) => {
const [email, setEmail] = useState(props.email);
return (
<div>
<input type="text" name="email" />
</div>
);
}
function App() {
const emailField = EmailField({ email: ''});
const [sendEmail, setSendEmail] = useState(false);
return (
<div>
<input type="checkbox" name="subscribe" />
<label>Subscribe to newsletter</label>
{/* this is wrong */}
{sendEmail && emailField}
{/* this is correct */}
{sendEmail && <EmailField />}
</div>
);
}
/******
^
if not done correctly:
- React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks
********/
// @3.0 - Conditional Rendering
const App = () => {
const [product, setProduct] = useState([]);
// wrong way
return <div>{product.length && product.name}</div>; // this would show 0 if product.length is 0
// better 1
return <div>{product.length ? product.name : null}</div>;
// better 2
return <div>{!!product.length ? product.name : null}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment