Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
Is this how closure works in useState hook?

I am trying to understand how to implement useState hook using pure Javascript. and I stuck at the part where the closure is used.

here is the code.

    const React = (function () {
      let hooks = [];
      let idx = 0;

      function useState(initVal) {
        const _idx = idx;
        console.log(_idx) // 0, 1

        const state = hooks[idx] || initVal;

        const setState = newVal => {
          hooks[_idx] = newVal;
        };

        idx++;
        return [state, setState];
      }

      function render(Component) {
        idx = 0;
        const C = Component();
        C.render();
        return C;
      }

      return { useState, render };
    })();

    function Component() {
      const [count, setCount] = React.useState(1);
      const [text, setText] = React.useState('apple');

      return {
        render: () => console.log({ count, text }),
        click: () => setCount(count + 1),
        type: (word) => setText(word),
      }
    }

    var App = React.render(Component); // {count: 1, text: "apple"}
    App.click();
    var App = React.render(Component); // {count: 2, text: "apple"}
    App.type('pear');
    var App = React.render(Component); // {count: 2, text: "pear"}

When setState function(click or type) is called, it updates value of hooks array according to their index which is 0 for count and 1 for text.

Which means setState function inside useState remembers the value of _idx of each state(count and text) by javascript closure?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Which means setState function inside useState remembers the value of _idx of each state(count and text) by javascript closure?

Yes. When useState is called, it gets the next available index using idx and stores it in the constant _idx. The setState function returned forms a closure because of which it remembers the _idx corresponding to its state even though useState has finished execution.

I stuck at the part where the closure is used.

Other places where closure is used:

  • useState and render functions inside the React module form a closure over hooks and idx. Hence the functions are able to read/write to these variables even after React (an iife) has finished execution.
  • render, click and type functions form a closure. The render method closes over Component. Hence it is able to access count and text even after Component function has finished execution. Similarly, click and type form a closure and hence can invoke setCount and setText funtions which were defined inside Component scope.
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda