Hooks
Hooks
Example:
function Regulator() {
const [value, setValue] = useState(0);
return <>
<Button title="Decrease"
onPress={() => setValue(value - 1)} />
<Text>Volume: {value}</Text>
<Button title="Increase"
onPress={() => setValue(value + 1)} />
</>
}
useEffect(() => {
storeValue(valueName, value);
});
return <>...</>
}
Example:
useEffect(() => {
setInterval(() => {
//...
}, 1000);
}, []);
return <>…</>;
}
Example:
useEffect(() => {
const timer = setTimeout(() => {…}, 1000);
return () => clearTimeout(timer);
}, []);
function Controller() {
const {x, setX} = useContext(XContext);
return <>
<Text>X: {x}</Text>
<Button title="-" onPress={() => setX(x-1)} />
<Button title="+" onPress={() => setX(x+1)} />
</>
}
function App() {
const [x, setX] = useState(1);
return <XContext.Provider value={{x, setX}}>
<View>
<Controller />
<Text>X squared: {x * x}</Text>
</View>
</XContext.Provider>
}
16 AC3040: Mobile Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Exercise
Modify the theme-
switching app to use
context
The app should
contain several child
components whose
appearance is
updated according to
the theme
function MyComponent() {
const [num, setNum] = useState(0);
const [light, setLight] = useState(true);
const result = intCal(num);
return ...
}
const result =
useMemo(() => intCal(num), [num]);
return ...
}
rendering diffing
and
updating
return <>
<Text>X: {x}</Text>
<Button title="-" onPress={decrease} />
<Button title="+" onPress={increase} />
</>
}
return <>
<Text>X: {x}</Text>
<Button title="-" onPress={decrease} />
<Button title="+" onPress={increase} />
</>
}
Returns the same function if the dependency is not changed
useMemo(…) returns a value, while useCallback(…) returns a function
memo(…) may need to be used together with useCallback(…)
Would be more useful when the optimized components are big
23 AC3040: Mobile Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Exercise
Add debugging logs to previous examples and check the
difference when using and not using useMemo,
useCallback and memo
console.log("render");
return <button onClick={handler}>Click</button>;
}
Note that useRef is also useful to hold a reference to
DOM HTML elements when working with the web
25 AC3040: Mobile Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Exercise
Create a stopwatch: a counter increasing every second,
and two buttons to stop/restart it
Hint: use useRef to keep a reference to the timer handle