Search code examples
reactjs

How can I set the function to a state without the function being called?


I'm trying to set a function to a state. The problem I'm having, is that when I set the state the function gets called. How can I set the function to a state without the function being called?

const [submitCallbackFunction, setSubmitCallbackFunction] = useState();

Child Component

props.setSubmitCallbackFunction(scrollToSection); // Don't call scrollToSection when setting setSubmitCallbackFunction

function scrollToDonationSection() {
    ...
}

Solution

  • Here is an example of how to do this although, I don't know if it should be solved this way:

    Code Sandbox

    import React, { useState } from "react";
    import ReactDOM from "react-dom";
    
    import "./styles.css";
    
    const function1 = () => console.log("Func 1!");
    const function2 = () => console.log("Func 2!");
    
    const ChildComponent = ({ setSubmitCallbackFunction }) => {
      return (
        <button onClick={() => setSubmitCallbackFunction(() => function2)}>
          Update!
        </button>
      );
    };
    
    const App = () => {
      const [submitCallbackFunction, setSubmitCallbackFunction] = useState(
        () => function1
      );
    
      return (
        <div className="App">
          <button onClick={submitCallbackFunction}>Test submit func</button>
          <ChildComponent setSubmitCallbackFunction={setSubmitCallbackFunction} />
        </div>
      );
    };
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);