hpal007
hpal007

Reputation: 313

useEffect with local variable

I am trying to call useEffect funtion onchange of local variable, but its not working is only works if i use it with useState variable, I know there might be some basic thing here that I am not aware of. sandbox link: https://codesandbox.io/s/affectionate-gareth-igyv7?file=/src/demo.js

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

export default function Demo() {
  const [value, setValue] = useState("");
  let valueOne, valueTwo;

  const setValueOne = (value) => {
    valueOne = value;
  };

  useEffect(() => {
    console.log(value);
    console.log(valueOne);
  }, [value, valueOne]);

  return (
    <div>
      <h1>Demo</h1>
      <input
        placeholder="useState"
        onChange={(e) => setValue(e.target.value)}
      />
      <input
        placeholder="function"
        onChange={(e) => setValueOne(e.target.value)}
      />

      {/* {console.log(valueOne)} */}
    </div>
  );
}

Upvotes: 2

Views: 4335

Answers (1)

Tanisk jha
Tanisk jha

Reputation: 31

setValueOne will not rerender your component, If you want to fire a re-render, useEffect function needs to have a useState which basically hold state between re-renders.

You can try managing your state like below, its more readable and it will work too.

import React, { useState } from "react";
import "./styles.css";

export default function Demo() {
  const [valueOne, setValueOne] = useState("");
  const [valueTwo, setValueTwo] = useState("");

  const handleValueOne = (e) => {
    setValueOne(e.target.value);
  };

  const handleValueTwo = (e) => {
    setValueTwo(e.target.value);
  };

  return (
    <div>
      <h1>Demo</h1>
      <input
        value={valueOne}
        placeholder="useState"
        onChange={handleValueOne}
      />
      <input
        value={valueTwo}
        placeholder="function"
        onChange={handleValueTwo}
      />

      {/* {console.log(valueOne)} */}
    </div>
  );
}

Upvotes: 2

Related Questions