Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a state from useState without triggering useEffect hook

The problem

I want to prevent the triggering of a useEffect hook which contains a useState value in the dependency array. To make it clear, look at the example.

Detailed explanation

In the initialization process a form will set some values therefore I defined a flag to prevent the other effect to execute before it is fully initialized, but I also don't want to trigger the second effect when the initialization flag state is changed.

Can I somehow prevent the tracking of this isInitialization state? I couldn't find a thread which is solves my problem. Would you maybe so kind to link the threads which are related to that? Thanks in advance.

Example

export function SomeComponent(props) {
  const [form] = useForm();
  const [settings, setSettings] = useState(props.initialSettings);
  const [isInitialization, setIsInitialization] = useState(true);

  /**
   * Updates the form settings state, just for initialization
   */
  useEffect(() => {
    if (isInitialization) {
      form.setFieldsValue({
        ...settings,
      });
      setIsInitialization(false); // <-- This should not trigger any useEffect
    }
  }, [settings, form, isInitialization]);

  useEffect(() => {
    if (props.settingsChanges && !isInitialization) {
      props.settingsChanges(settings, isValid && hasRequiredFields);
    }
  }, [settings, props, isInitialization]);
}

like image 507
Ling Vu Avatar asked Oct 20 '25 10:10

Ling Vu


1 Answers

Try to delete isInitialization from dependency array.

  useEffect(() => {
    if (isInitialization) {
      form.setFieldsValue({
        ...settings,
      });
      setIsInitialization(false); // <-- This should not trigger any useEffect
    }
  }, [settings, form]);

As React docs says:

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

UPDATE:

Building Your Own Hooks

Building your own Hooks lets you extract component logic into reusable functions.

If it is common logic, then you can create custom hooks and share across components.

«useMyCustomHook.jsx» file:

import { useEffect } from 'react';

export default function useMyCustomHook(str) {
  useEffect(() => {
      console.log(`title`, title);
  });
}

and then use it in component:

function fooFunction(props) {
  const [firstName, setFirstName] = useState('');

  useMyCustomHook(`This is ${firstName}`);

  return (        
      <div>The firstname is {firstName}</div>
  );
}
like image 196
StepUp Avatar answered Oct 21 '25 22:10

StepUp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!