The useState() hook in React is designed to manage local state within a single component. By default, states cannot be directly shared between components using useState() alone, as the state is local to the component in which it is defined.
We can use Lifting State Up method:
You can move the state to a common ancestor component, and then pass the state and setter function down to child components via props. This way, both child components can access and modify the shared state.
const ParentComponent = () => {
const [sharedState, setSharedState] = useState(0);
return (
<div>
<ChildComponent1 sharedState={sharedState} setSharedState={setSharedState} />
<ChildComponent2 sharedState={sharedState} />
</div>
);
};