< Previous: Changing a React Component's State with setState()   Next: Rendering an Array of Data with map() and JSX >

State and the Single Source of Truth

Before we go any further, there's an important bit of theory you need to be aware of. Don't worry, I'll keep it short!

When you're starting out you probably think the idea of having state inside components is neat – after all, it keeps functionality and relevant data together in one object, right?

It's true that isolating things this way can be a useful way to break large apps into smaller pieces, but at the same time it can get awfully complicated. Where is all that data stored? Is it duplicated? If it is duplicated, how do you make sure all values are updated correctly when one changes? When you get to the kind of scale Facebook works to – they have over 10,000 React components! – this becomes a brain vortex.

The solution in idiomatic React – i.e., code that was written the way an experienced React developer would write it – is to have what's called a single source of truth, which is one master state for most if not all of your application, then send that state down as props to your child components.

Using this technique, when any part of that master state changes it will automatically update the props of your child components, and the changes will flow down in one direction from top to bottom – always synchronized, never duplicated.

In the perfect React world, few if any components have state. And so React has a special syntax to create components that are nothing more than a render() method – they can't have state or any methods, they just accept some props and render them. Here's a basic example:

const FunctionalTest = (props) => {
    return {props.message};
};

Once that's in your code, you can use it like any other component:

<FunctionalTest message="Hello from a functional component!" />

Don't kill yourself trying to avoid state. Instead, be a pragmatic programmer: go for stateless components where possible, but state is there to be used when you really need it.

Buy the book for $10

Get the complete, unabridged Hacking with React e-book and take your learning to the next level - includes a 45-day no questions asked money back guarantee!

If this was helpful, please take a moment to tell others about Hacking with React by tweeting about it!

< Previous: Changing a React Component's State with setState()   Next: Rendering an Array of Data with map() and JSX >

Copyright ©2016 Paul Hudson. Follow me: @twostraws.