Luna
Luna

Reputation: 33

How to avoid init function call when first rendered in React.js?

When my first rendered, the callback will be called and set to the initial value, how could I avoid my callback been called when first rendered? (Because it's meaningless to set to initial value again when the data is get from database)

I hope callback will only run when value changes

App.js

  const [on, setOn] = useState(initOn);

  useEffect(() => {
    callback(on);
  }, [on, callback]);

  return (
    <div className={`App ${on ? "light" : "dark"}`}>
      <h1>Hello CodeSandbox</h1>
      <button onClick={() => setOn((prevState) => !prevState)}>Click Me</button>
    </div>
  );
}

index.js

const onChangeMode = mode => console.log(`changes to mode ${mode}`);

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App initOn={true} callback={onChangeMode} />
  </React.StrictMode>,
  rootElement
);

My codesandbox link : code

Upvotes: 1

Views: 944

Answers (1)

95faf8e76605e973
95faf8e76605e973

Reputation: 14191

You could have some conditions inside your useEffect

useEffect(() => {

  // at this point, this is true when you first render the component
  // in a real application, this condition should probably be if(on === undefined)
  if (on === true) {
    return;
  } else {
    callback(on); // only execute the callback when you fetch data from db
  }
}, [on, callback]);

Upvotes: 1

Related Questions