70 %
Chris Biscardi

SwiftUI @State property wrapper vs React useState

export const meta = { tags: ["swiftui"] }

useState vs @State

In React we could have a component that shows a series title and the current episode's title while also rendering a PlayButton sub-component.

const PlayerView = ({ episode }) => {
const [isPlaying, setPlaying] = useState(false);
return (
<div style={{ display: "flex", flexDirection: "column" }}>
<PlayButton isPlaying={isPlaying} setPlaying={setPlaying} />

Not how this is similar to the way that @State works. We can specify a private var wrapped with @State.

When the state value changes, the view invalidates its appearance and recomputes the body. - swiftui/state

struct PlayerView: View {
var episode: Episode
@State private var isPlaying: Bool = false
var body: some View {
VStack {
PlayButton(isPlaying: $isPlaying)

In both cases, changes to the state cause a "re-render" of the component. In Swift's case, the @State is a wrapped value, which is why we have to access the projected value using $isPlaying when passing it to the PlayButton component.

The behavior of how we're passing in isPlaying is slightly different, so I've included setPlaying in the React example whereas the isPlaying value could be manipulated by the PlayButton in the swift example.