Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my component's local state affected by changes in the global state?

I have 2 components sitting side by side: Local and Global.
Local has a local state and Global has a global state.

  1. I click Local: Local’s state updates.
  2. 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your Local component gets redeclared each time MyApp re-renders because it’s defined within MyApp‘s body. Move it outside of MyApp and this problem will go away.


function Local() {
  const [local, setLocal] = useState(0)
  return (
    <button onClick={() => setLocal(1)} >
      {local}
    </button>
  )
}


export default function MyApp() {

  const [global, setGlobal] = useState(0)

  function Global() {
    return (
      <button onClick={() => setGlobal(1)}>
        {global}
      </button>
    )
  }

  return (
    <>
      <Local /> <Global />
    </>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading