You are on page 1of 25

State Management in React Native

01. APP Overview

Red
‘Red’ ‘Green’ ‘Blue’ → Data that is changing
More Red
Number → Type of the States
Less Red

Green 0 → Starting point of the States


More Green

Less Green
/* 3 Different Pieces of States
We also need how different pieces of states coordinate */
Blue

More Blue

Less Blue

RGB values will be increased and decreased to get a color in a box.

Buttons with “Red”, “Green” and “Blue” are almost the same except the labels. So, we can use Resuable Component.

And also, we will see how states and props work with Resuable Components.

We create SquareScreen under src/screens folder.

Do required definitions in App.js file.

1
Create a button in HomeScreen.js and attach it to SquareScreen.

Test. Ok.

02. Reusable Color Adjuster


Since Red, Green, Blue buttons are the same, we will create a common component named as ColorCounter.js:

“rnfes”:

2
Let’s pretend that we only have the color Red button and use it without prop.

Use this resuable component, ColorCounter in SquareScreen for three 3 times:

Test. Ok. 3 Red Buttons are displayed.

3
Now, use props and send Text values to the component. With prop named “color”, we pass the labels for the
buttons.

And now go to the Component and catch the prop.

Normally we catch the props as shown below. “color” prop is in the “props” object.

But we will use destructuring and extract “color” from “props” object and use it in the component.

Backtick: AltGr + Ctrl “,” Then Press Space

4
Test. Ok.

Last thing we have to do is add in (create) state variables and modify them from the Button elements.

QUESTION: Where are we going to place these state Variables?

Are we going to create them in ColorCounter or in SquareScreen?

03. Coordinating States


Now, we have ColorCounter Component and SquareScreen component showing it.

We need 3 State Variables: Red, Green, Blue.

Where do we create these state vars, in SquareScreen or in each of the component?

SquareScreen

(Red) (Green) (Blue)


ColorCounter ColorCounter ColorCounter

In SquareScreen we need 3 State Vars for rgb(). And this is going to be used as backgroundColor property.

And ColorCounters should change these values.

GENERAL RULE for these kind of cases:


We create State Vars in the most parent component that needs to read and change the state value.

In our case, SquareScreen is the Most Parent Component. Then we create the State Vars in SquareScreen
component.
5
QUESTION: Since we are creating the State Vars in SquareScreen, how will the ColorCounter object update
the these State Vars?

In this case, State Vars are going to be passed as Props.

SquareScreen

{value:Red} {value:Blue}
{value:Green}

(Red) (Green) (Blue)


ColorCounter ColorCounter ColorCounter

Rule: If a child needs to read a state value, the parent pass it down as a prop.

In our case, child component doesn’t need to read the State Vars in parent Component. Reading or Printing
the current values are not needed.

What about if a child component ColorCounter needs to change the parents (SquareScreen) State Var?

CALLBACK FUNCTION: Parent send a Callback function to child.

SquareScreen

{onChange: () =>{}} {onChange: () =>{}} {onChange: () =>{}}

(Red) (Green) (Blue)


ColorCounter ColorCounter ColorCounter

ColorCounter function can invoke that function and make change to that state var.

That will change the value of the state var → that causes Rerendering

Whenever Parent is rerendered all the children are also rerendered.


First Test managing states between different components

In the next lesson, we will see how to pass these callback functions to child components to change the state vars in
parent component.

6
04. Passing Callbacks to Children
We established two important facts:

We are going to create different state variables in SquareScreen. And we will send callback functions to
ColorCounter to update these state vars in parent component

Import useState in SquareScreen.

Create State Vars:

Red, green, blue state vars are defined and initialized to zero.

7
Now, we have to give to the components the ability to change these state vars. Send CallBack functions.

We send 2 Callback function to each Component. One for Increase and one for Decrease.

Catch these props in ColorCounter Component using destructuring.

Use them in Component:

When onPress realized, CallBack function is called.

Actually we might think that onIncrease and onDecrease has {() => setRed(red + 1)} and {() => setRed(red - 1)}
statements in it and passed down.

8
When setRed is called, SquareScreen is rerendered. Let’s put a console.log to
see the value of state var.

We will see the values of red increases and decreases. But, we would not want it below zero or more then 255.

Test. Ok.

Callback function running. Whenever a state var is updated then the component is rerendered. Parent and Children
are also rerendered.

Next lesson, we erase console.log and do the same things for Green and Blue.

9
05. Tying State Values Together
Now apply the same callback functions to other ones:

Test. Ok. Buttons are working.

Now create our Box:

Test. Ok. At the beginning, Red Green Blue values will be 0, 0, 0 and the color Black. Let’s try to increase them . It is
going to be very slow.

10
Let’s use 15 and define it as a constant.

Apply it:

Test. Ok. Color increase is fast.

Values should be between 0-255. Next lesson, We have to put a control for that.

11
06. Validating State Changes
Values should be between 0-255. We have to put a control for that.

These controls will be in callback functions.

We don’t want that:

• Repeated Code
• Hard to read the JSX code

We will use HELPER FUNCTION.

12
Test. Ok. Working…. Not going over 255 and down below zero.

Next lesson add Green and Blue and refactor Helper Function.

07. Reusable State Updates


Add Green and Blue and refactor Helper Function.

Use SWITCH instead if statement:

Save the file. Test for red. Ok.

13
Hard to read it. Refactor it with ternary expression:

null: return nothing.

Test it for red. Ok.

Refactor setColor helper function for other colors:

14
Use setColor function for other ColorCounter Components:

Test. Ok. We condesed down everything

15
08. Handling Text Input

Show a Text Input


Enter Name:
When a user types in Input Box show the
input immediately underneath the Input Box
Your Name is:

If the user enters ‘s’, ‘s’ is going to be displayed: a → a, ‘al’ → al, ‘alp’ → alp …..

New screen: TextScreen. Attach it to App.js:

16
Create a button in HomeScreen:

Test. Ok. Working….

17
09. Showing a Text Input
Import TextInput Component:

Test it. TextInput does not show up. !!!!!!!!!


It is there but we can not see it. Type in you will see. TextInput is actually there.

By default it has zero style. We have to add style to it.

18
10. Two Important Props
Capitalization: In IOS, input by default gets capitalized. Depending on the version in Android it could be capitalized
also, or not.

Auto Correction: Generally we would want it. But, in email, username, passwords, we don’t want it.

Test. Ok.

11. Weird Things with Text and States


How to read the text and print it to screen.

TextScreen

TextInput

{currentText: “asdasd”}

We have a TextScreen displaying TextInput in it. Let’s accept that TextInput has a state property tied to it. Name
could be currentText. When we enter a value like “asdf”, the value of this state becomes this. In reality, TextInput
does not have a state var.

19
What if we want TextScreen to inspect the value of TextInput?

TextScreen

I want to check the value of


my child
TextInput

{currentText: “asdasd”}

I want to check the value of my child and show it on my screen. In react we can not do it. Parent can not access to
the child and read a value in it.

Then what do we do for that?

We will have a State Var for the child component. This State Var represents the content current in this TextInput.

TextScreen
{currentText: “asdasd”}

{value: currentText
onChangeText: () => {} }

TextInput

20
Everytime we render this TextScreen, we will show this TextInput and send these two Props.

1. Step

value: Value of the State Var in TextScreen. TextInput will get this value automatically and display it.

In the Input field “Alparslan Horasan” will be displayed as default.

2. Step

Send Callback Function: TextInput is coded to get this prop.

Any time the user types in, this callback function is invoked. In this CallBack function, we have a state var
and we can call the setter func. Any time the user changes the data in the TextInput, we want our State var
to be updated also.

Any time a state var is updated the component is rerendered.

And also we pass a new value to TextInput, which is the updated text that the user just entered.

Rightnow, we don’t have any problem running TextInput. The problem is that how we pass this value to
TextScreen?

In React we don’t have a mechanism to access child from Parent. Instead, child accesses parent with this
callback mechanism. We send this callback function to child as a prop. Whenever somethings happen in the
Child, Child calls this callback function and tells the parent that something has just occured.

21
12. Updating State
Add a state var to TextScreen Component.

Import useState Hook from React.

Create a State Var in the Component.

Send this State Var ‘name’ to TextInput as a prop and set it’s value directly. As parent we want to tell the
child what the current value it will have.

We send {name} as a prop:

Test. WE CAN’T TYPE ANYTHING AT ALL.

Whenever we type something everything disappears.

22
Whenever we change to Input value, TextScreen is rerendered with an empty string. The Input string is going
to be an empty string. To change this, we should let the TextInput component to call setName function.
setName will update the name state var and rerendereing will happen with this value.

Sending Callback Function as a prop:

Whenever we pass this onChangeText as prop, CallBack Function is called with a parameter named as
newValue. This value becomes the currrent value in Input area. With this newValue using setName we
update the name state var. Then TextScreen is rerendered with this new value.

Test. Ok. Running…..

Aim is to access a value in TextInput from TextScreen.

Now we can display it in JSX within a Text in TextScreen.

23
Change code enter “Enter Name:”

This a template. Whenever a TextInput is used, use it this way.

13. Exercise
Enter Password

Password Must be longer


than 5 Chars

If the user enters more than 5 chars, then let that err message go away.

We need to conditionally render some JSX elements. How?

To execute JS statement we use { }

if true show “That was true”, Otherwise do nothing (null)


24
14. Exercise Solution

25

You might also like