Sometimes, we want to share states between components using the useState hook in React.
In this article, we’ll look at how to share states between components using the useState hook in React.
How to share states between components using the useState hook in React?
To share states between components using the useState hook in React, we can lift the state up to the component that contains both components.
For instance, we write
const Ancestor = () => {
const [count, setCount] = useState(1);
return (
<>
<DescendantA count={count} onCountChange={setCount} />
<DescendantB count={count} onCountChange={setCount} />
</>
);
};
to add the count state and set that as the value of the count prop of the DescendantA and DescendantB components.
Conclusion
To share states between components using the useState hook in React, we can lift the state up to the component that contains both components.