liveBook · Manning

Initial state

As explained in React Hooks in Action: With Suspense and Concurrent Mode

Initial state is the state value supplied when a stateful component or state-management mechanism is first initialized.

Initial state is the value supplied when a stateful component or state-management mechanism is first initialized. With React's useReducer, it works with a reducer to produce the component's first current state; later dispatches produce updated state and trigger rendering. section 3.2.3 section 3.2

Use initial state to establish the values and relationships a component needs before interaction:

  • Pass a reducer and initial-state value to useReducer; receive the current state and dispatch function. section 3.2.3
  • Treat the initial-state arguments as initialization inputs: React uses them on the component's first invocation and ignores them on subsequent invocations. section 3.2.3
  • Represent related values together when actions update them together, such as group, selected index, details visibility, and bookables. section 3.2.2

Generating initial state from a prop

A WeekPicker derives its first week object from a date by passing getWeek as useReducer's initialization function: const [week, dispatch] = useReducer(reducer, date, getWeek); This separates state generation from the component and runs expensive generation only during initialization. section 3.3.4

const [state, dispatch] = useReducer(reducer, initialState);

Inspect the minimal useReducer call that pairs a reducer with initial state and destructures the returned state and dispatch function. section 3.2.3

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains first-call initialization, subsequent argument ignoring, object state, and initialization functions, without detailing React internals.
Examples
Uses BookablesList state objects, a WeekPicker week derived from a date, and BookablesView state lifted from a child component.
What it assumes
Assumes familiarity with React components, useState, props, JavaScript objects, and array destructuring.
What you can do after
Apply it via useReducer to define initial component values and derive them with an initialization function when needed.
How it connects
Connects initial state with useReducer, reducers, actions, dispatch, component rendering, and props.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.