Get to Know State

We’d like to allow users to edit the word counter text. For this, we need some way to handle values that change over time: a classic book asserts that an object has state if its behavior is influenced by its history (Structure and Interpretation of Computer Programs [AS96]).

Let’s take a little detour to understand state. Open your browser’s JavaScript console and type the add function, which just adds its arguments together and returns the result:

 function​ add(x, y) {
 return​ x + y;
 }

Then call the add method a few times:

 add(1,2); ​// returns 3
 add(5, 7); ​// returns 12
 add(1, 2); ​// returns 3 again
 add(5, 7); ​// returns 12 again

The return value of add depends only on its arguments, because it is a pure function.

Now type the addS function, which multiplies the second argument by n before adding it to the first argument, and increments n each time you call it.

 let​ n = 1;
 
 function​ addS(x, y) {
 const​ result = x + n * y;
  n++;
 return​ result;
 }

The return value changes each time you call addS, even if the arguments stay the same, because the return value depends on how many times you’ve called addS. addS has a history: it stores state in the n variable.

The potential for bugs grows as the program grows. State complicates applications, as the same function, with the same arguments, can return different results based on when you call it.

We never tried to update a component’s props inside the component itself, for a good reason: inside a React component, props are immutable (in practice, you can assign a new value to a prop inside a component, but it won’t have any effect). To handle state, you need an additional mechanism. One good option is learning the tools that React itself provides. They get the job done in the majority of situations with little boilerplate.

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

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