Demystifying React Components State

Originally published at: http://www.sitepoint.com/demystifying-react-components-state/

React is the new kid on the block, which means that not many people have any real-world experience of building something with it. This article will focus on components state and when to use them.

An example will be used as the basis for our exploration. A simple blog with a list of categories which when clicked display a list of articles. Data will be hard-coded to begin with, while later we’ll use Socket.IO to simulate external article publication.

Stateless Children, Stateful Parent

Let’s start this article by citing what the React documentation says about this topic:

A common pattern is to create several stateless components that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props.

How do we begin to implement this pattern? Phrasing it another way, the pattern involves a hierarchy of parent and child components.

Each component will be in a separate file to enhance modularity. We’ll use Browserify to:

  • deliver one bundled JavaScript file to the browser
  • prevent global namespace pollution (i.e. on the window object in case of the browser)
  • support CommonJS modules (i.e. module.exports that we see in Node.js code)

Let’s start our example looking at the bottom of the hierarchy by identifying the ideal candidates for stateless child components.

Continue reading this article on SitePoint

Is it possiple from an owner component to retrieve the state of an ownee?

It’d be possible by using a function passed to the child component but it’s totally against the methodology followed by React.

if you need to access the state of a child component, then the state probably should belong to the parent. The state should be passed as a prop to the child and if you want to modify the state of the parent from the child, you should pass in the function from the parent through a prop.

Perhaps there are use cases where this is not ideal, but I have not encountered it yet.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.