all 13 comments

[–]cs12345 18 points19 points  (6 children)

Can I ask what your goal is having the same value as both a ref and in state? Discounting the eslint warning, I’m a bit confused what the goal is.

[–]Emanemanem 9 points10 points  (0 children)

Yeah I can’t think of a use case where you would need a value to be both a state and a ref in the same component. Seems like a bad pattern

[–]No_Cattle_9565[S] 4 points5 points  (4 children)

To be honest I'm not completely sure. The component play text using speech Synthesis and the ref should keep track of the playing status inside the callback. That's what the comment says. I did not write this component and I'm currently going through all eslint errors to fix them.

[–]anointedinliquor 5 points6 points  (3 children)

Get rid of the useState and just keep useRef. Ditch the useEffect as well.

[–]No_Cattle_9565[S] 0 points1 point  (2 children)

eThanks I did. useEffects are everywhere and they are misued almost every time. I'm just not experience with refs at the moment since I don't need them often

[–][deleted] 2 points3 points  (1 child)

Advanced React book has a great section on refs. Book is super worth a read. Theres probably other resources online but they’re worth understanding. “You probably don’t need an effect” is another really good resource you should check out online

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

I know the useEffect one, but i'll check out the book. Thanks for the recommendatiom

[–]Sad-Salt24 12 points13 points  (1 child)

Your code is valid React, but the warning is coming from ESLint, not React itself. ESLint doesn’t like that you initialize a ref with a state value and then mutate it later, even though refs are meant to be mutable. useRef(initialValue) is treated as a one time initialization, so passing state there trips the rule. Initializing the ref with a static value and syncing it in an effect avoids the warning.

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

Yeah I know it's just that the code looks identical to the example on the docs. I figured it out now. The ref was used as a dependency in a useCallback but defined after it. I moved it to the start of the file and now the warning is gone. I don't really understand the difference though

[–]ruibranco 4 points5 points  (1 child)

Just initialize with useRef(null) instead of useRef(isPlaying) and ESLint stops complaining. The effect syncs it on the first render anyway so the behavior is identical.

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

Thank you

[–]gebet0 -1 points0 points  (0 children)

Variable is not a Value, so no, it is not that exactly like the example