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.

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

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

swift
struct PlayerView: View {
var episode: Episode
@State private var isPlaying: Bool = false
var body: some View {
VStack {
Text(episode.title)
Text(episode.showTitle)
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.