I have 2 components sitting side by side: Local and Global.
Local has a local state and Global has a global state.
- I click Local: Local’s state updates.
- I click Global: Global’s state updates and Local’s state reverts to its initial state.
export default function MyApp() {
const [global, setGlobal] = useState(0)
function Local() {
const [local, setLocal] = useState(0)
return (
<button onClick={() => setLocal(1)} >
{local}
</button>
)
}
function Global() {
return (
<button onClick={() => setGlobal(1)}>
{global}
</button>
)
}
return (
<>
<Local /> <Global />
</>
);
}
// Initial render: 0 0
// Click on Local: 1 0
// Click on Global: 0 1
Why is this?
2
Answers
In react there’s no such thing as global state.
The above line has two issues: a) it can’t be defined outside the component function scope; b) as I mentioned every state is LOCAL. Remember that. If you are interested at global state, search "state management for React".
Your
Local
component gets redeclared each timeMyApp
re-renders because it’s defined withinMyApp
‘s body. Move it outside of MyApp and this problem will go away.