React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at some tips for writing better React apps.
React.useState
doesn’t reload state from props.
It can only set the initial state.
If we need to update the state as props change, then we need to use the useEffect
hook.
For instance, we can write:
function Avatar({ username }) {
const [name, setName] = React.useState(username);
React.useEffect(() => {
setName(name);
}, [username])
return <img src={`${name}.png`}/>
}
We get the username
prop .
And we set it as the initial value of the name
state with useState
.
Then we use the useEffect
hook to watch for changes in the name
value.
We watch it for changes, then call setName
to set the name with the latest value of username
as the name
‘s new value.
Then we can use name
in the JSX we render.
#javascript #software-development #web-development #technology #programming #react native