Home > Blockchain >  Why useState/useEffect didn't works?
Why useState/useEffect didn't works?

Time:01-17

0I did many research and tests but I don't understand why my useState and my re-render with useEffect doesn't change. For my project I use React nextJs. As you will see, in my console I've a log who tells me "I'll become TRUE" but value stay FALSE an d my useEffect returns : "I pass on the effect with this value : FALSE"

// IMPORTS //
...
import React, { useEffect, useState } from "react";


//FUNCTION PART //

function ContactMe({ pageInfo }: Props) {
  const [val, setVal] =useState(false)
  
  const changeVal = () => {
    console.log("I've this :", val);
    
    if (val === false) {
      console.log("I'll become TRUE");
      setVal(true)
    } else{
      console.log("I'll become FALSE");
      setVal(false)
    }
  };
  useEffect(() => {
    return console.log("I pass on the effect with this value :", val);

  },[val])

  console.log("Value is :", val)


//JSX PART //

return (
  <div>
  ...
        <p>My value is : {val}</p>
        <button onClick={() => changeVal()}>Click here</button>
  ...
  </div>
)

Tx in advance for your help !

Sometimes value change but after few seconds it stops to work :( This is an exemple of my real case where I try to exchange a send button on mail to a loading button during the sending.

CodePudding user response:

Heres a working piece, the return value was not needed. Also the function can be condensed to literally 1 line:

import React from 'react';

function ContactMe() {
  const [val, setVal] = React.useState(false);
  React.useEffect(
    () => console.log('I pass on the effect with this value :', val),
    [val],
  );

  return (
    <div>
      <p>My value is : {val}</p>
      <button onClick={() => setVal(!val)}>Click here</button>
    </div>
  );
}

export default ContactMe;
  • Related