Timo Jokinen
Timo Jokinen

Reputation: 726

React useEffect weird behavior

I have a form component that gets its state from its parent. The form component just renders a few input fields and others.

The parent component uses useReducer and passes the values down to the form component.

There are two parent components one that lets the user create with the form and one that lets them edit.

In the edit parent component i use useEffect to fetch data from an api and set the initial state from the server.

In development build it sometimes breaks when the component is rendered with the following error:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

and in production build it breaks every time when the component is rendered.

const Form = ({ state, dispatch }) => {
    return ...form elements;
}

const ParentComponent = ({ match }) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    useEffect(() => {
        fetchData = async () => {
            const data = await apiCall(match.params.id);
            dispatch({ type: 'overwrite', value: data });
        }

        fetchData();
    }, [match.params.id]);

    return <Form state={state} dispatch={dispatch} />
}

I have no clue what I'm doing wrong. I also tried to put fetchData on root level and wrap it with useCallback but it has no impact.

Upvotes: 0

Views: 808

Answers (1)

Komo
Komo

Reputation: 2138

Looks good to me, here is a codesandbox: https://codesandbox.io/s/6jj92nm0k. I suggest stripping down your code to something similar to this exemple and work your way back to your original code step by step.

Upvotes: 1

Related Questions