How to pass state between components
How do I pass state to a child component? How can I get state from a child component to a parent?
A decision we constantly have to make when developing a React app, is how to share state between multiple component. There are a lot of tools and patterns that we can use to tackle this problem. However, sometimes we can get to a better solution by removing instead of adding.
If you don't have multiple components, you don't have to worry about passing state between them.
Ask yourself, do I really need this to be a component?
If you don't intend on reusing it across multiple different components, and it isn't so complex that it's hard to reason unless it is isolated, then you probably don't need it to be it's own component.
As an alternative, to keep your code readable, we can just have our previous child components be variables inside the parent component. Using this method all previous components will have direct access to the intended state, which means we no longer have to worry about passing it.
Below is an example of what it looks like to use variables instead of components.
function CounterPage() {
const [counter, setCounter] = useState(0);
const header = (
<header>
<h1>This is a page for a counter</h1>
</header>
);
const counterValueSection = (
<section>
<h2>Counter value</h2>
<p>{counter}</p>
</section>
);
const counterControllersSection = (
<section>
<h2>Counter controllers</h2>
<button type="button" onClick={() => setCounter((c) => c + 1)}>
+
</button>
<button type="button" onClick={() => setCounter((c) => c - 1)}>
-
</button>
</section>
);
return (
<div>
{header}
{counterValueSection}
{counterControllersSection}
</div>
);
}
Next time you're faced with the decision of how to pass state between components, ask yourself if you really need to have multiples components, or if they can just be one.
You'll be amazed by how easy your life will get if you try to solve problems by removing instead of adding.