Sharing State

Hooks and useState work cleanly when the state is completely encapsulated inside one component, but often components have to share state. Sometimes state is shared among just one subtree of DOM elements on the page, but sometimes state is shared across a page. I’ll talk about more complex state patterns in Chapter 11, ​Managing State in React​, but here we will cover the simplest version of one common scenario where state is shared among parent and child components.

In this React pattern, when there is a common parent to all the components that need that state, the state is typically owned by the common parent. The parent sends the raw values down to the child components as props and typically also sends a function that the ...

Get Modern Front-End Development for Rails, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.