Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
What is the different between state hook vs assign to local variable?

Coming from class-based object-oriented language C#, I can assign an object to a local variable so I can use it later. But in this example, when I assign it to a local variable, it will not render. When I console log the tempPersonObj inside the handleClick, it will print the object. But it will print empty object inside the PersonDetails function.

App.js

import React, {useState} from "react";

const persons = [
  { 
    "name": "Arto Hellas", 
    "number": "040-123456",
    "count": 3,
    "id": 1
  },
  { 
    "name": "Ada Lovelace", 
    "number": "39-44-5323523",
    "count": 10,
    "id": 2
  },
  { 
    "name": "Mary Poppendieck", 
    "number": "39-23-6423122",
    "count": 17,
    "id": 3
  }
]

const PersonDetails = ({person}) => {
  console.log(person)
  return (
    <div>
      <p>-----------------</p>
      <p>{person.name}</p>
      <p>{person.number}</p>
      <p>{person.count}</p>
    </div>
  )
}

const App = () => {

  const [view, setView] = useState(false)
  const [personObj, setPersonObj] = useState({})
  let tempPersonObj = {};

  const handleClick = (person) => {

    //This will work
    // setPersonObj(person)

    //This will not work
    tempPersonObj = person
    console.log(tempPersonObj)

    setView(true)
  }
  return (
    <div>
      <h1>List:</h1>
      {persons.map((person) => {
        return (
        <div key={person.id}>
          {person.name} {""}
          <button onClick={() => handleClick(person)}>View</button>
        </div>
        )})
      }

    {/* This will work */}
    {/* {view && <PersonDetails person={tempPersonObj}/>} */}

    {/* This will not work */}
    {view && <PersonDetails person={personObj}/>}

    </div>
  );
}

export default App

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

React components work by rendering UI as a function of state and props. The tempPersonObj local variable is neither state nor props and is redeclared each render cycle.

In other words, you can mutate tempPersonObj in the handleClick callback and it will update, but when the setView(true) state update is processed and the component rerenders, tempPersonObj is redeclared an empty object. It's a completely new variable unrelated to the tempPersonObj from the previous render cycle.

const App = () => {
  const [view, setView] = useState(false);
  const [personObj, setPersonObj] = useState({});

  let tempPersonObj = {}; // new variable each render cycle

  const handleClick = (person) => {
    //This will work
    // setPersonObj(person)

    //This will not work
    tempPersonObj = person
    console.log(tempPersonObj) // <-- see object mutation

    setView(true)
  }

  return (
    ...

    tempPersonObj // empty object again on next cycle

    ...
  );
}

If you need to update a person object it necessarily needs to be part of React state so it is retained from render cycle to render cycle.

const App = () => {
  const [view, setView] = useState(false);
  const [personObj, setPersonObj] = useState({});

  const handleClick = (person) => {
    setPersonObj(person);
    setView(true);
  }

  return (
    ...
  );
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda