Using the state

Now that we know how the state works, it is important to understand when it should be used and when we should avoid storing a value in the state.

If we follow the rules, we can easily figure out when a component should be stateless or stateful, and how to deal with the state to make our component reusable across the application.

First of all, we should always keep in mind that only the minimal amount of data needed should be put into the state.

For example, if we have to change a label when a button is clicked, we should not store the text of the label, but we should only save a Boolean flag that tells us if the button has been clicked or not.

In that way, we are using the state properly, and we can always recalculate different values according to it.

Secondly, we should add to the state only the values that we want to update when an event happens, and for which we want to make the component re-render.

The isClicked flag is an example of that, and another one could be the value of an input field before it gets submitted.

In general, we should store into the state only the information needed to keep track of the current user interface state, such as the currently selected tab of a tabbed menu.

Another way to figure out whether the state is the right place to store information is to check if the data we are persisting is needed outside the component itself or by its children.

If multiple components need to keep track of the same information, we should consider using a state manager such as Redux at the application level.

We will now look at the cases where we should avoid using the state if we want to follow the best practice guidelines.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.77.71