I've just started with Solidjs (coming from React) and I have encountered some strange behaviour. When I have multiple returns, global state is not working. In the case below:
const Test = () => {
const [user, setUser] = useUserContext()
if (!user()) return null
return (
<div>
<div>
{user()? user()?.username : "No user"}
</div>
</div>
)
}
if the user is set from another component, this component still returns null (the user is null initially). But if I move that if logic inside the last return (i.e. have only one return), then it works. Why is this happening?
Could not find any resources where this behaviour was mentioned.
Early returns do not work for SolidJS components because components are executed once when they are loaded. Unlike React, there is no component level re-rendering in SolidJS.
You can use expression like ternary operator or use built-in components like
ShoworSwitch/Matchfor conditional rendering.User is guaranteed to exist inside
Showcomponent, so that, we can use non-null assertion for performance:Alternatively you can wrap the component in a memo, so that force re-rendering using the memoized value.