Why can't I have early returns in Solidjs?

88 views Asked by At

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.

1

There are 1 answers

0
snnsnn On BEST ANSWER

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 Show or Switch/Match for conditional rendering.

const Test = () => { 
  const [user, setUser] = useUserContext();
  return user() ? <div>{user()?.username}</div>: <div>No User</div>;
}

User is guaranteed to exist inside Show component, so that, we can use non-null assertion for performance:

const Test = () => { 
  const [user, setUser] = useUserContext();
  return ( 
    <Show when={user()} fallback={<div>No User</div>}> 
      <div>{user()!.username}</div>
    </Show>
  )
}

Alternatively you can wrap the component in a memo, so that force re-rendering using the memoized value.

const Test = createMemo(() => { 
  const [user, setUser] = useUserContext()

  if (!user()) return null
  return ( 
    <div> 
      <div>
      {user()? user()?.username : "No user"}  
      </div>
    </div>
  )
});