1

I have a function below which i used as an array dependency to a useEffect handler

const handleInputUpdate = (event) => {
    const eventValue = event.target.value;
    setState({ ...state, answer_text: eventValue, trigger: true })
    // console.log("I am changing for no reason")
  }

Below is the useEffect handler

  useEffect(() => console.log(" I am changing for no reason in useeffect"), [handleInputUpdate])

What i want is the useEffect handler to run only when the handleInputUpdate function is called but it runs also on component mount.

Here's what i've observed

  1. The handleInputUpdate function doesn't run on component mount but only i need it to
  2. Without respect to the above observation, the useEffect handler runs anyway.

Here's what i've tried

  1. I tried consoling a text inside the handleInputUpdate function to see whether it runs on component render but it doesn't.

Even though the function doesn't run, the useEffect handler triggers anyway which is not what i want.

How can i solve this ?

Thanks in advance

2 Answers 2

3

useEffect dependency array is not used to trigger the effect when a function is called; the elements of the array are observed for any change and then trigger the effect.

In this case, handleInputUpdate will change on every render because it is not memoised, so the effect will also run on every render.

Since handleInputUpdate changes the state when it is called, you are better off adding that state to your useEffect dependency array:

useEffect(() => {
  if (answer_text && trigger) {
    console.log("I am changing for a reason in useeffect")
  }
}, [answer_text, trigger])
Sign up to request clarification or add additional context in comments.

1 Comment

with the logic given to me by both parties, i was able to resolve my problem. Thanks guys
3

The handleInputUpdate function, while it doesn't run on render, looks like it's created when the component runs, just before rendering. Since it won't be === to the value last in the dependency array - the handleInputUpdate from the prior render - the effect callback will run.

You need to observe changes to the answer_text value in state instead.

useEffect(() => {
  // ...
}, [state.answer_text]);

I would also recommend separating out your state into different variables - these aren't class components, don't feel like you have to mash everything together into a single object structure.

const [text, setText] = useState('');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.