Reputation: 3971
I have 2 components and a hook. I want those components to share the same state through the hook. I created this simple codesandbox https://codesandbox.io/s/peaceful-resonance-inxbcz?file=/src/hook.js , (when you click a button it adds an item to an array), but as I see those components have separate states. Is there a simple way to use one state for all of those components? UP: In my live app, those components are far away from each other, on different pages. Thanks
Upvotes: 0
Views: 534
Reputation: 384
If you want to share you should use useState instead of useRef as useRef dont trigger component updates.
On the other hand here is an example of what i think you are trying to achieve:
export default function App() {
const UseCustomHook = () => {
const [count, setCount] = useState(0);
return [count, setCount];
};
const [counter, setCounter] = UseCustomHook();
const ComponentOne = ({ setCount, count }) => (
<button onClick={() => setCount((prev) => prev + 1)}>
Compo 1 {count}
</button>
);
const ComponentTwo = ({ setCount, count }) => (
<button onClick={() => setCount((prev) => prev + 1)}>
Compo 2 {count}
</button>
);
return (
<div className="App">
<ComponentOne count={counter} setCount={setCounter} />
<ComponentTwo count={counter} setCount={setCounter} />
</div>
);
}
if you need to share states trhough your app components on different levels then you should switch to useContext https://reactjs.org/docs/hooks-reference.html#usecontext
Upvotes: 1