Recently React introduced Hooks, and I was not at all in favour of functional components. I was so used to the class component that this change was not one I was looking forward too. Also, the latest version update was also a significant change. So I tried my hands with both at the same time.
Here is what I came up with. This is basically a trial of making a regular to-do app using React Hooks. So if you are a pro and are looking for something different, this blog is not for you.
Definitions
1. Hooks: Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. React provides a few built-in Hooks, like useState
and useEffect.
2. useState: It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState()
. This is similar to this.state.count
and this.setState
in a class, except you get them in a pair.
Examples how we can initialise states using useStateconst [count, setCount] = useState(0) // Number const [name, setName] = useState('James') // String const [data, setData] = useState([]) // Array
3. useEffect: By using this Hook, you tell React that your component needs to do something after rendering. Instead of thinking in terms of mounting and updating, you might find it easier to think that effects happen after render. React guarantees the DOM has been updated by the time it runs the effects.
By default, it runs both after the first render and after every update. It is similar to componentDidMount
and componentDidUpdate
, just cleaner and logical.
const App = ( ) => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
}
Introduction
We are going to create a normal to-do app using AsyncStorage.
Requirements
Create a new app with the latest version of React Native.
react-native init tasks
cd tasks
Now when you have created a new app, it’s time to import a few more components.
yarn add 'react-native-dropdownalert'; // To show alert messagesyarn add 'react-native-vector-icons'; // To use icons in the appyarn add '@react-native-community/asyncstorage'; // To use local database
Code Reference
Now remove everything in the App.js
file, and add the following code.
UseState explained
// Initialisation of state:this.state { name: 'James' }// Updating state value:this.setState({ name: 'Jeremy' });console.log(this.state.name); output: Jeremy // Now using hooks we can declare this as const [name,setName] = useState('James'); setName('Jeremy'); console.log(name);output: Jeremy
The same process is used to update a string, number, or an array. Nothing is different than the flow described above.
UseEffect explained
//before hookscomponentDidMount(){ AsyncStorage.clear(); retrieveData(); });// using hooksuseEffect(() => { AsyncStorage.clear(); retrieveData(); });
Here I am clearing the AsyncStorage using useEffect
and calling the retrieveData
function to get the value at the time of rendering of the app. There are many other ways to do this — feel free to read the React documentation for more use cases.
AsyncStorage use case
// Save data to AsyncStoragelet user = { name, email, phone, key: Math.random(), };const arrData = [user]; setData(arrData); await AsyncStorage.setItem('user', JSON.stringify(arrData));// Get data from AsyncStorageconst retrieveData = async () => { try { const valueString = await AsyncStorage.getItem('user'); const value = JSON.parse(valueString); setData(value); } catch (error) { console.log(error); } };