Skip to content

Commit

Permalink
Merge pull request #48 from li3zhen1/state_mixin
Browse files Browse the repository at this point in the history
[Doc] Add State Management and Eliminating Redundant Rerenders
  • Loading branch information
li3zhen1 authored Feb 23, 2024
2 parents f89e012 + bcb1bd5 commit f581962
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions Sources/Grape/Grape.docc/Documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Grape supports localization features. You can localize the labels in the graph v


* <doc:CreatingAForceDirectedGraph>
* <doc:StateManagementAndEliminatingRedundantRerenders>

* ``ForceDirectedGraph``

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# State Management and Eliminating Redundant Rerenders



## Control the state

You can control the view state like this:

```swift
import Grape

struct MyStatefulGraph: View {

// States including running status, transformation, etc.
// Gives you a handle to control the states.
@State var graphStates = ForceDirectedGraphState()

var body: some View {
ForceDirectedGraph(states: graphStates) {
// ...
} force: {
// ...
}
}
}
```

`ForceDirectedGraphState` utilizes the `Observation` framework so all you need to change the state is to mutate its properties:

```swift

graphStates.isRunning.toggle()

graphStates.transform = .identity // reset transform to identity

```

## Eliminate redundant rerenders

One trick to eliminate redundant rerenders is to not referencing any observed properties in the `body` of the `View`. Instead, try to reference the entire `Observable` object. This way, the `body` will not rerender when the observed properties change.

```swift
import Grape

struct MyStatefulGraph: View {

// States including running status, transformation, etc.
// Gives you a handle to control the states.
@State var graphStates = ForceDirectedGraphState()

var body: some View {
HStack {
ForceDirectedGraph(states: graphStates) {
// ...
} force: {
// ...
}
GraphStateToggle(graphStates: graphStates) // seperate views so we can reference the entire graphStates
}
}
}

struct GraphStateToggle: View {
@Bindable var graphStates: ForceDirectedGraphState
var body: some View {
Button {
graphStates.isRunning.toggle()
} label: {
// ...
}
}
}
```

Although this introduces boilerplates, but `Grape` do benifit from this pattern since its re-evaluation is expensive (especially with large graphs or heavy rich text labels).

> This might not always work for other `Observation` based state management.

0 comments on commit f581962

Please sign in to comment.