I need to pass value of state step from component Step to component App as I am going to pass that as a props to another child component (not presented in the code).
Initially, I tried to use lifting up, but could not synchronise step and count – count is less by 1.
The code is here: https://codesandbox.io/s/sparkling-violet-cn7glt
Then, I used useEffect hook,
code is here: https://codesandbox.io/s/kind-colden-pcthvq
and included step variable in dependency array, it worked but I suppose that the task might be solved by using only lifting states up without useEffect, would be grateful for your advices.
2
Answers
It might be a bit overwhelming to control your states in that way. Let’s consider to use Context component.
React Docs – Context
It allows to avoid heavy prop drilling and gives clearer and better way to control your states (in case when you do not want to use some third party State Management Systems).
Pseudocode
Quick Example:
MyContext.js
App.js
MyChildComponent.js
Also I made some small refactory of you code so go and have a look (starting from MyContext.js file). In there I wrote some comments below so you can follow the steps.
REFACTORY – SANDBOX
If you find yourself trying to synchronize two states with eachother, it’s often sign that they shouldn’t be two states in the first place. Instead, just have one state. The child components should use the props they’re given directly and not copy them into states which then need to managed independently.