React - helping you succeed with initial issues
🍱Framework
javascript
react
Using state where you don’t need state.
- Doesn’t believe that props do cause re-renderings.
- Short videos where I fix code.
Mutating React state
Problem: Filling array with values.
.push()only mutates state, doesn’t create new one..concatwould cause too many state updates.
From
useEffect(() => {
let isSubscribed = true;
usersService
.find()
.then(users => {
if (isSubscribed) {
setUserList([]);
for (const user of users.data) {
currentUserList.push([
<MenuItem
key={user.username}
value={user.username}>
{user.username}
</MenuItem>,
]);
}
}
})
.catch();
return () => {
isSubscribed = false;
};
}, [userList, navigate]);over
useEffect(() => {
let isSubscribed = true;
usersService
.find()
.then(users => {
if (isSubscribed) {
setUserList([]);
for (const user of users.data) {
setUserList(currentUserList =>
currentUserList.concat([
<MenuItem
key={user.username}
value={user.username}>
{user.username}
</MenuItem>,
])
);
}
}
})
.catch();
return () => {
isSubscribed = false;
};
}, [userList, navigate]);to
From using the pre-computed userList (in useEffect hook):
<Select
...
>
{userList}
</Select>to:
<Select
...
>
{userList.map(user => (
<MenuItem
key={user.username}
value={user.username}>
{user.username}
</MenuItem>
))}
</Select>No clear separation between UI and Data logic
- Fill state with array of JSX elements…
Using state when you don’t have to
Example 1: Missing trust in props
Note: props are reactive! -> They originate in state or context somewhere!
const MyComponent: React.VFC<MyComponent> = props => {
const [dialogOpen, setDialogOpen] = useState(false);
useEffect(() => {
setDialogOpen(props.open);
}, [props.open]);
const [parameterTitle] = useState(props.parameterTitle ?? '');
const [parameterKey] = useState(props.parameterKey);
const [parameterType] = useState(props.parameterType ?? 'number');
const parameterState = {};
parameterState[props.parameterKey] = props.parameterValue;
const [parameterValue, setParameterValue] = useState(
parameterState[parameterKey]
);
}Three things:
dialogOpenstate +useEffecthook are completely useless. Just destructure.parameterTitle,parameterKey,parameterTypeare useless. Just destructure with default values.parameterStateis confusing.
Example 2: Derived values in React
Note: State should store data! It should not store derived values. That is, it should not store values which can be generated by a change in the data. For example, styles or components etc., components etc. That’s part of the UI.
Explanation: State or props changes will cause re-renders of the component. Therefore the other values will be re-computed with their new values.
Discuss on Twitter ● Improve this article: Edit on GitHub