React: State, Props, and Keys

As I mentioned in another post, my team and I are building a front-end for a Rails job search application. I dove into the project not knowing very much about React, and frankly confused about the various concepts. State and props were confusing areas for me, and we had some warnings for not having keys for child components. So, I will discuss some of those major points.

State

According to the Facebook docs, state should “contain data that a component’s event handlers may change to trigger a UI update.” So, if the state of a component changes, the component will update. For instance, here is a CRUD app that displays a name and body for posts. These should be included in state since they are being changed so often:

this.state = {
name: "",
body: "",
};

Here is the method we call to update name and body after a click event:

updateProperties(e) {
const { name, value } = e.target;
this.setState({ [name]: value });
}

Seems to be pretty straightforward- reserve state for data that should trigger a UI change when it updates.

Props

Props are passed from parent to child components. Here is an example from our job search app:

<ul>
{job.raw_technologies.map((technology) => {
return (
<Technology key={technology.id} technology={technology.name}/>)
})}
</ul>

Here we are mapping over an attribute of jobs (an array- raw technologies). For each item in the array, we are setting a key for the child element and a property- technology.name. Here is the Technology function that is called and returns <li> elements:

const Technology = ({technology}) => {
return (<li>{technology}</li>)
}

You can also pass them to components using the spread operator. From the Facebook docs:

var props = {};
props.foo = x;
props.bar = y;
var component = <Component {…props} />;

Keys

React also likes your child elements to have keys. We achieved this by having a unique key for each child element (same code from above):

return (
<Technology key={technology.id} technology={technology.name}/>)
)

We didn’t think we needed a key for a simple array of children, but apparently strange things can happen if you don’t give keys to the children. From the Facebook documentation: “When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).” Providing keys to children allows React to make minimal DOM changes. If we didn’t pass keys to the technology list, and the list needed to be updated, we would have to re-render the entire job posting (instead of the technology list elements).

Conclusion

React is a strange and wonderful playground, and it’s taking some getting used to. But, it’s such a DOM slayer! Definitely worth learning and using.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.