Can anyone explain how to initialize a value via the useState hook from the store where user information is stored? After the first rendering it returns undefined
const [lastName, setLastName] = useState<string|null>(store.user.lastName);
I’ve used useEffect. But idk how to do this without using react hooks
useEffect(() => {
setLastName(store.user.firstName)
}, [store.user]);
2
Answers
If your state will be always as the other variable and change accordingly to
store.user.lastName
, just pass it as props to the component.Say you have
UserCard
component where you have the problemThen you need to refactor it to:
and use it like
<UserCard lastName={store.user.lastName} />
If you’re facing the issue of
undefined
after the first render and you’re using useState to initialize lastName with a value from your store, it’s likely because the store’s user data isn’t populated at the time of the component’s initial render.In that case, you can handle it like this:
In this case, any time
store.user.lastName
changes, the useEffect will run and update your local state with the new value.Now as you said "without using react hooks", so if you want to avoid hooks entirely, consider using a class component with state management in lifecycle methods like
componentDidMount
andcomponentDidUpdate
.Here is how you can do that:
Although this last one is not recommended, so try to use with hooks.