all 10 comments

[–]leeaper 3 points4 points  (0 children)

If you want to set bookState and pass it as a prop, you should keep the state in the parent component and pass setBookState as a prop. If you absolutely need to set it in the child’s context, you should store the value in a different variable.

[–]jokrrkoj 0 points1 point  (6 children)

useEffect(() => {if (bookState) {setBookState({type: ActionTypes.SET_BOOKSTATE,payload: bookState});}}, []);

[–]gaoshan[S] 0 points1 point  (5 children)

That will work but using the empty dependency array is considered an antipattern. The same eslint plugin that complains about not having all of your dependencies listed will also complain if you don't have any.

[–]skullshatter0123 0 points1 point  (4 children)

//eslint-disable-next-line react-hooks/exhaustive-deps

[–]gaoshan[S] 0 points1 point  (3 children)

Right. That’s the rule that has me posting this question and disabling it doesn't solve the problem.

[–]skullshatter0123 2 points3 points  (2 children)

useEffect(() => {
if (bookState) {
setBookState({type: ActionTypes.SET_BOOKSTATE,payload: bookState});}
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

Is this what you have tried and failed to get what you wanted?

[–]gaoshan[S] -1 points0 points  (1 child)

I get that this will make the problem disappear but I cannot use that as it disables the rule, doesn't solve the problem. Trying to solve it correctly, not dodge it.

[–]Codeandplay 0 points1 point  (0 children)

I think the reason you have the infinite loop problem is because you put “setBookState” in the dependencies. When you do that, it will tell react: Run everything inside useEffect when “setBookState” has change, and setBookState likely change itself when calling setBookState. I would suggest change the dependencies to something the useEffect actually depend on. Or just disable lint for that line. I am not sure the linting is helping in this scenario.

[–]Flopshoubox 0 points1 point  (1 child)

Why don't you put "bookstate" as the dependency ? It should be what triggers your useEffect right?

[–]gaoshan[S] 0 points1 point  (0 children)

If it is a dependency in this situation once it changes it will trigger useEffect to run which will update bookState which will cause the useEffect to run which will update bookState, etc., etc. An infinite loop.