I have a main app and two components. It looks something like this:
MainApp:
const MainApp = () => {
return (
<>
<Component1 />
<Component2 />
</>
);
};
Component1:
const Component1 = () => {
const [state, setState] = useState(false)
return (
<>
<button type="button" onClick={() => setState(state => !state)}>Toggle</button>
</>
);
};
Component2:
type Props = {
state?: boolean;
};
const Component2 = ({ state }: Props) => {
return (
<>
{state ? <p>Hello</p> : <p>Not hello</p>}
</>
);
};
Right now it obviously doesn't work since Component2
doesn't get the state
from anywhere.
My problem is, how do I share the state between the two components, with the MainApp
being the intermediary ? Do I create the useState
variable in the MainApp
instead of Component1
, and then pass the state
and setState
to the toggle component (Component1)
, and pass the state to Component2
, or is there a better way to do this ?