Categories
React Answers

How to share states between components using the useState hook in React?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.