1

I'm learning useEffect and useCallBack hooks. What I'm trying to do is add a function in the useCallBack, and make sure that the screen will not call this function until I click on a button. Here is my sample code below. Currently, it calls the function inside useEffect before I click on the button. My goal is to click on the button then trigger the useEffect function with useCallBack function. Still new to this, thanks for helping out.

import React, {useState, useEffect, useCallback} from 'react';
import {Button, StyleSheet, View} from 'react-native';

const submitHandler = useCallback(() => {
    console.log('the inputs tracking');
  }, []);

  useEffect(() => {
    console.log('Should not be work until submitHandler button is clicked');
  }, [submitHandler]);

return (
    <View>
      <Button title="Click me" onPress={submitHandler}></Button>
    </View>
)
Yuze Sun
  • 63
  • 1
  • 6

1 Answers1

1

I would think you wouldn't need to call submitHandler from useEffect - just delete the useEffect block and perform all the logic in submitHandler.

You're seeing the useEffect run because all useEffects will run on the first render.

If the useEffect is somehow necessary, you would need an additional state to track if the button was clicked.

const [clickCount, setClickCount] = useState(0);

const submitHandler = useCallback(() => {
  console.log('the inputs tracking');
}, []);

useEffect(() => {
  if (clickCount > 0) {
    submitHandler();
  }
}, [clickCount, submitHandler]);

return (
  <View>
    <Button title="Click me" onPress={() => setClickCount((x) => x++)}></Button>
  </View>
);

The onPress callback increments the count, which will trigger the useEffect and call submitHandler. Although, I think this is unnecessary and a single useCallback provided to onPress is the right way to go.

Additional comment about your code:

Adding submitHandler in useEffect dependency array does not mean the effect will run when submitHandler is called. The useEffect will run whenever submitHandler changes (it's object reference) and since its dependency array is empty it will never change. This means the useEffect will only fire on the first render.

lurvey
  • 167
  • 7