Don't store JSX in React States or Variables
- The state should always be a serializable javascript object. JSX gets converted to React objects with
React.createElement()
at compile time by babel. And these objects are not always serializable. - Don't create UI elements manually with
React.creteElement()
it's hard to read, Write your UI elements in JSX in the return statement - Always write your JSX in the return statement, never in variables or states, never outside of the return statement.
DON'T 💩🧨💣
function Greet() {
const [greet, setGreet] = useState(<div>Say Hi</div>);
const change = () => setGreet(<div>Say Hello</div>);
return (
<>
{greet}
<button onClick={change}>change</button>
</>
);
}
DO ✅
function Greet() {
const [greet, setGreet] = useState('Hi');
const change = () => setGreet('Hello');
return (
<>
<div>Say {greet}</div>
<button onClick={change}>change</button>
</>
);
}
No Constants in components
Never define constants inside the components, It can cause performance issues, sometimes visible, noticeable performance issues.
Define them outside the components, preferably in different files, and then import them to use inside your components.