I’m trying to render different fragments onto a page in a sequential way (A > B > C), and am wondering what the best practice is in terms of using state variables to control the rendering of these components
Currently I have it set up as a single state variable: const [screen, setScreen]
and am applying conditional rendering:
screen === 'page1' ? <Component1 />
: screen === 'page2' ? <Component2 />
...
: 'Page Not Found'
However, I am concerned this might lead to re-rendering of each component when screen
is updated (or would this not happen because screen
isn’t passed into the component itself?). Would having a separate state variable to trigger each screen be more efficient? For example:
const [showPage1, setShowPage1] = useState(false)
const [showPage2, setShowPage2] = useState(false)
...
{showPage1 && <Component1 />}
{showPage2 && <Component2 />}
...
In general I’m confused on how to reduce state variables and am wondering if clustering them together is a bad practice as it may lead to unnecessary re-renders. For example:
- Storing user data in
useContext
– updating one key updates the entire state and will likely trigger re-renders in multiple components - Storing validation check and input values in an object to avoid having a state variable for each individual input
Please advise on whether it’s appropriate to consolidate similar state variables in the above context
2
Answers
There is no definitive answer to this question, as different methods may have different advantages and disadvantages depending on the context and complexity of your application.
But I think this is a simple and straightforward way to implement sequential rendering, as you only need to update one state variable to switch between screens or steps.
The two approaches do exactly the same thing, the only difference is the number of
useState
hooks you are usingwhen a state update occurs in the parent component it will rerender and then check what to return based state value.
having one or two states makes no difference.
there are some alternatives and packages as Formik that can help you do this, but it is ok to make a state for inputs and if you want a good performance you want to avoid rerendering the whole component so you can create a child component only for your form so it rerenders on its own
This will rerender mounted components using the context and we want to do that to track user changes