# Slices and keys

A slice owns one piece of state: its initial value and the reducers that turn an action into the next value.

## Reducers

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/SlicesGuideTests.cs#L7-L23

```csharp
public sealed record Settings(string Theme, int FontSize);

[ActionType("settings/theme-changed")]
public sealed record ThemeChanged(string Theme);

public sealed record SettingsReset;

public sealed class SettingsSlice : Slice<Settings> // key "settings"
{
    public SettingsSlice()
    {
        On<ThemeChanged>((state, action) => state.Theme == action.Theme ? state : state with { Theme = action.Theme });
        On<SettingsReset>(_ => Initial);
    }

    protected override Settings Initial => new("light", FontSize: 14);
}
```

- `On<TAction>((state, action) => ...)` reduces with the action; `On<TAction>(state => ...)` when the action carries no data. Register them in the constructor, one per action type.
- Actions match by **exact type**: a handler for `ThemeChanged` never runs for a type derived from it. An abstract type, an interface or `object` is rejected (DUCKY005).
- Return the same `state` reference when nothing changes. The store compares references, so an unchanged reference commits nothing and notifies nobody. `state with { }` is always a new reference, so it always commits and re-runs that slice's selections. Their `onChange` still fires only when the projected value changed.
- Reducers must be pure: no I/O, no clock, no random, no mutation of the state or the action. The analyzers flag these (DUCKY001 to DUCKY003). Work that leaves the store belongs in an [effect](effects.md).
- A reducer that throws commits nothing: the store dispatches `ReducerFailed` and keeps running.
- State types are classes (`TState : class`), and two slices can't share one.

## Keys

Every slice has a key, used by persistence, cross-tab sync, DevTools and `State.Get(string)`. By default it is derived from the class name: one trailing `Slice`, `Store`, `Reducers` or `Reducer` is stripped, then the name is kebab-cased.

| Class | Key |
|---|---|
| `TodoSlice` | `todo` |
| `ShoppingCartReducers` | `shopping-cart` |
| `UIStateSlice` | `ui-state` |
| `CartStore` | `cart` |
| `Features.TodosSlice` (nested) | `features-todos` |

Override `Key` to pin it, so that renaming the class doesn't change it (persisted data is stored under the key). A key is lowercase letters and digits in `-`-separated words. A generic slice class must override `Key`.

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/SlicesGuideTests.cs#L27-L38

```csharp
public sealed record Layout(bool SidebarOpen);

public sealed record SidebarToggled;

public sealed class LayoutSlice : Slice<Layout>
{
    public LayoutSlice() => On<SidebarToggled>(state => state with { SidebarOpen = !state.SidebarOpen });

    public override string Key => "app-layout"; // pinned: renaming the class keeps the key

    protected override Layout Initial => new(SidebarOpen: true);
}
```

Two slices with the same key are a configuration error, reported at the first store resolution with every other problem found.

## Register and read

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/SlicesGuideTests.cs#L49-L58

```csharp
await using var services = new ServiceCollection()
    .AddDucky(ducky => ducky.AddSlice<SettingsSlice>().AddSlice<LayoutSlice>())
    .BuildServiceProvider();
var store = services.GetRequiredService<IStore>();

await store.DispatchAsync(new ThemeChanged("dark"));

var theme = store.State.Get<Settings>().Theme;               // "dark"
var layout = (Layout)store.State.Get("app-layout");          // by key
var settingsSlice = services.GetRequiredService<SettingsSlice>(); // the store-owned instance
```

`AddDuckyGenerated_{Assembly}()` makes the `AddSlice` calls for you. Each slice is also injectable: `AddSlice<SettingsSlice>()` registers `SettingsSlice` as the store-owned instance.

## Action names

DevTools and `ActionContext.ActionType` show an action as `Namespace.Name`. `[ActionType("settings/theme-changed")]` gives it a readable name instead, as on `ThemeChanged` above.

## Actions and state as C# 15 unions

A C# 15 `union` of record cases is a natural action set. Dispatching the union value dispatches its case: reducers, effects, middleware and `ActionContext` all see `AddProduct`, not `ParcelAction`, so handlers match exactly as before. Register one `On<T>()` per case; `On<ParcelAction>()` is a configuration error ([DUCKY319](../../diagnostics/DUCKY319.md)). A default union has no case and fails like a `null` action.

Source: https://github.com/phmatray/Ducky/blob/v2/test/Ducky.Docs.Tests/Core/UnionActionsGuideTests.cs#L6-L24

```csharp
public sealed record AddProduct(string Sku);

public sealed record EmptyParcel;

public union ParcelAction(AddProduct, EmptyParcel);

public sealed record Parcel(int Items);

public sealed class ParcelSlice : Slice<Parcel>
{
    public ParcelSlice()
    {
        // One handler per case, never On<ParcelAction>(): dispatch unwraps the union to its case.
        On<AddProduct>(state => state with { Items = state.Items + 1 });
        On<EmptyParcel>(_ => Initial);
    }

    protected override Parcel Initial => new(0);
}
```

A union inside a state record serializes through the System.Text.Json resolver you pass to `UseJson`, like any other state type; cases that share a JSON shape need a type classifier on your side.
