Home > Software engineering >  Reassignment of variables react
Reassignment of variables react

Time:03-07

Playing around with React, what is the logic behind the reassignment of variables not changing. For example when creating a var didClick assigning it to false and then changing the var didClick to true when we click on the display button my component still does not list out all the task text.

function App() {

  /*var didClick = false*/
  var [didClick,setdidClick] = useState(false);
  const [tasks,setTasks]  = useState([
    {
        id: 1,
        text:'Doctors Appointment',
        day:'Feb 5th at 2:30pm',
    },
    {
        id: 2,
        text:'Cat Appointment',
        day:'Feb 5th at 4:30pm',
    },
    {
      id: 3,
      text:'Dog Appointment',
      day:'Feb 5th at 7:30pm',
  }
])


  const functiontoClick = () => {
    /*didClick = true*/
    setdidClick(true)
  }

  return (
    <div>
        <button onClick={()=> functiontoClick()}>Display</button>
        <div>
          {didClick ? tasks.map((task) => (
            <li key={task.id}> {task.text} </li>
          )) : null }
        </div>
    </div>
  );
}


export default App;

CodePudding user response:

using useState will ensures that the component has been updated and calls for re-rendering of the component in react. but using normal declaration using var, const and let will not update or re-render the component. you can see what happened if you add console.log just before the return.

first case using useState:

var [didClick,setdidClick] = useState(false);
...
  const functiontoClick = () => {
    /*didClick = true*/
    setdidClick(true)
  }
console.log({ didClick }) 
 return (
...

the console will return false at first render and after clicking will console true and render the component.

second case using var:

var didClick = false;
...
  const functiontoClick = () => {
    didClick = true
  }
console.log({ didClick }) 
 return (
...

the console will return false at first render and after clicking will not console anything because it's not rendering the component again

CodePudding user response:

As pointed out in the comments it is unclear what you are asking for: but for your example, if you wanna toggle the display you can use the following code:

const [didClick,setdidClick] = useState(false);
 <button onClick={()=> useState(!didClick)}>Display/Hide</button>

If your code at the moment you are not using the functionality being provided by useState:

  • Related