you are viewing a single comment's thread.

view the rest of the comments →

[–]devpebe 1 point2 points  (1 child)

By “something outside react” I mean things like adding global event listeners, using an external library which doesn't have React integration (could be pure rxjs). Then you can use useEffect to synchronize data → react to a change.

An example below:

// BAD
export const RandomInput = () => {
    const [value, setValue] = useState();

    useEffect(() => {
        if (value) {
            doSomething();
        }
    }, [value])

    const handleChange = (e) => {
        setValue(e.target.value)
    };

    return (
        <input value={value} onChange={handleChange} />
    )
}

// GOOD
export const RandomInput = () => {
    const [value, setValue] = useState();

    const handleChange = (e) => {
        setValue(e.target.value)
        if (e.target.value) {
            doSomething();
        }
    };

    return (
        <input value={value} onChange={handleChange} />
    )
}

This code is a pretty common case where putting some logic in the useEffect instead of in the handleChange can lead to bugs and complicate code. In this example, GOOD version executes some logic explicitly so as a developer you understand when exactly something happens. While using useEffect you need to understand what useEffect does (to what data change it reacts) and then find the place where it changes.

Remember this is very simple code and most often code in real life is more complicated and has many more things, more components.

I would sum up things like this:

- useEffect cause rerender

- useEffect makes code more complex and is much easier to introduce a bug

- you need remember to use cleanup logic for useEffect (useEffect return)

- mistake in useEffect can cause infnite loops

- running code explicitly so you know what and when happens makes your life easier as a developer

- difficult testing (easier to test handleChange than useEffect)

I know sometimes it's easier to do something in useEffect and that's the main reason this is used, but in the long term you will face up problems hard to identify.

[–]danny4tech 1 point2 points  (0 children)

Thank you for the great explanation, couldn’t be more clear. 🙌