skip to Main Content

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?

2

Answers


  1. In react there’s no such thing as global state.

      const [global, setGlobal] = useState(0)
    

    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".

    Login or Signup to reply.
  2. 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 />
        </>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search