Blackbonny
Blackbonny

Reputation: 89

Why useEffect is not called, when props have changed, render is called?

I have useEffect and I don't understand why useEffect is not called, when props have changed, but render is called. I have something like this, 'block' is object:

const { block } = props;

useEffect(() => {
    setTimeout(() => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
    });
}, []);

Thank you for helping! Now, I have next question) My inputRef is null, when block is changed and render is called:

const { block } = props;

const inputRef = useRef(null);

useEffect(() => {
    setTimeout(() => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
    });
}, [block, inputRef]);
...
<SomeComponent
  inputRef={inputRef}
 />

Upvotes: 0

Views: 540

Answers (2)

westfalensgod
westfalensgod

Reputation: 74

You can get this behavior by passing a block property as the second parameter in your useEffect function:

const { block } = props;

useEffect(() => {
    setTimeout(() => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
    });
}, [block]);

Don't forget that you can pass more properties:

useEffect(() => {}, [block, otherProperty])

Upvotes: 1

Thales
Thales

Reputation: 346

Because you have no parameters on your useEffect. If you pass the second parameter as an empty array, it will only fire when the component is mounted.

Here is a reference from the official docs

Upvotes: 3

Related Questions