reactjs etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
reactjs etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

7 Mayıs 2020 Perşembe

React Native (12) - Hooks yapısı ve useMemo() ile methodun cache'ten yanıt vermesi.

Marhaba,
bu yazımda React hooks  ile birlikte gelen useMemo fonksiyonunu inceleyeceğiz.  React Native ile geliştirilen uygulamada bir ekranda birden fazla değişkenin  state değerinde  değişiklik yapılıyorsa varsayılan olarak her bir değişiklikte ekranın tamamı render edilir.
Eğer bu ekranın bağımlı olduğu methodlar fazla zaman alacak işler yapıyorsa ekranın yanıt verme süresi de buna bağlı olarak  uzayabilir. Hooks yapısında bu durumunu çözümü için useMemo methodu kullanılmaktadır. useMemo methoduna cache leyeceği methodu ve hangi değişkenlerin değeri güncellendiğinde yeniden çalışacağı bildirilerek gereksiz yere  re-render işleminden kaçılabilir.

Bu yazı için geliştirilen örnek uygulamada bir Product'ın price(fiyat) ve count(adet/miktar) değerlerini tutacak şekilde CounterHooks adında bir component oluşturulmuştur.  Ekrana price
ve count değerlerini değiştirecek 2 adet button eklenmiştir. Bu butonlar kullanılarak fiyat değiştikçe ekran hemen render edilmektedir. Ancak sayı(count) değiştiğinde girilen delay time kadar bekleme yapılıp ekran öyle render edilmektedir. Eğer burada useMemo methodu kullanılmasaydı fiyat arttığında da state değişikliği olacağı için  gereksiz yere calculateColor(...) methodu çağrılarak delay time kadar render da bekleme olacaktır.

Durumu daha iyi kavrayabilmek için aşağıdaki adımları inceleyebilirsiniz. Veya git üzerinden daha detaylı CounterHooks component'ini inceleyebilirsiniz.

Aşağıdaki adımları takip ederek kendi projenizde uygulayabilirsiniz.

ilk olarak react native ile bir proje oluşturun.
$ react-native init someProject

Terminal üzerinden projenin bulunduğu dizine gidin.
$ cd someProject

kök dizindeki App.js dosyasının içeriğini aşağıdaki şekilde güncelleyin.

import React, {Component, useState, useMemo} from 'react';

import {View, StyleSheet, Text} from 'react-native';
import {AppButton} from 'appComponent/Button';

export default class App extends Component {
  render() {
    return <CounterHooks />;
  }
}

export const CounterHooks = () => {
  const [count, setCount] = useState(0);
  const [price, setPrice] = useState(1000);

  const delay = millisecond => {
    const startPoint = new Date().getTime();
    while (new Date().getTime() - startPoint <= millisecond) {
      console.warn('sleeping...');
    }
  };

  const calculateColor = () => {
    delay(1500);
    return count % 2 === 0;
  };

  const isBlue = useMemo(calculateColor, [count]);

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
        {isBlue ? 'blue' : 'yellow'} color selected
      </Text>
      <AppButton        style={[styles.btn, {backgroundColor: isBlue ? 'blue' : 'yellow'}]}
        title={`increment Count - (${count})`}
        onBtnPress={() => setCount(c => c + 1)}
      />

      <AppButton        style={styles.btn}
        title={`increment Price - (${price})`}
        onBtnPress={() => setPrice(c => c + 5)}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    margin: 10,
    top: 50,
  },
  btn: {margin: 10, backgroundColor: 'skyblue'},
  paragraph: {
    fontSize: 14,
    maxHeight: 60,
    margin: 10,
    padding: 0,
  },
});


count değerinde bir değişiklik olmadığı sürede useMemo cache ten yanıt vererek methodun içindeki hesaplamayı yeniden çalıştırmaz.

const isBlue = useMemo(calculateColor, [count]);




Kendi bilgisayarınızda yaptığınız çalışmada useMemo methodunu kaldırarak price değişikliği durumunda da ekranın yavaş render edildiğini görebilirsiniz.

1.5 sn bekleyerek methoddan değer dönülmektedir.

const calculateColor = () => {
  delay(1500);
  return count % 2 === 0;
};






"Increment Count" ve "Increment Price" butonlarına basarak aradakı hız farkını gözlemleyebilirsiniz.

github(state) : https://github.com/lvntyldz/tutorials/tree/11-react-hooks-usememo/react-native-hooks-examples

github(projenin tamamı) : https://github.com/lvntyldz/tutorials/tree/master/react-native-hooks-examples

kaynak : https://usehooks.com/useMemo/

4 Mayıs 2020 Pazartesi

React Native (7) - Hooks ve ClassComponent ile state güncelleme esnasında geçmiş değer(previous state) kontrolü

Marhaba,
bu yazımda yine React Native ile state object kullanırken bir önceki state değerini kontrol etmeyi inceleyeceğiz. Yine product objesi üzerinden örnekler yapılacaktır. Bu kez itemCount değeri değil price değeri hem ClassComponent yapısıyla hemde Hooks yapısıyla güncellenecektir.

ÖRNEK Product Objesi :
{title: 'iPhone 11',itemCount: 2,price: 1500}

ProductPriceValue ve ProductPriceValueHooks componentleri ile örnek açıklanmıştır. Github üzerinde bu componentleri inceleyebilirsiniz.

Aşağıdaki adımları takip ederek kendi projenizde uygulayabilirsiniz.

ilk olarak react native ile bir proje oluşturun.
$ react-native init someProject

Terminal üzerinden projenin bulunduğu dizine gidin.
$ cd someProject

kök dizindeki App.js dosyasının içeriğini aşağıdaki şekilde güncelleyin

import React, {Component, useState} from 'react';
import {Routes} from 'appEnum';
import {StyleSheet, Text, View} from 'react-native';
import {AppButton} from 'appComponent/Button';

export default class App extends Component {
  render() {
    return (
      <>
        <ProductPriceValue />
        <ProductPriceValueHooks />
      </>
    );
  }
}

export class ProductPriceValue extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: 'iPhone 11',
      itemCount: 2,
      price: 1500,
    };
  }

  handlePriceChange = () => {
    this.setState((prevState, props) => {
      console.warn('prevState : ', prevState);
      return {
        price: prevState.price + 101,
      };
    });
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph2}>
          state : {JSON.stringify(this.state)}
        </Text>
        <AppButton          style={{marginTop: 10}}
          title="increase item count"          onBtnPress={() => this.handlePriceChange()}
        />
      </View>
    );
  }
}

export const ProductPriceValueHooks = props => {
  const [state, setState] = useState({
    title: 'iPhone 11',
    itemCount: 2,
    price: 1500,
  });

  const handlePriceChange = () => {
    setState(prevState => {
      console.warn('prevState : ', prevState);
      return {...prevState, price: prevState.price + 100};
    });
  };

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph1}>state : {JSON.stringify(state)}</Text>
      <AppButton        style={{marginTop: 10}}
        title="increase item count"        onBtnPress={() => handlePriceChange()}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    margin: 10,
  },
  input: {height: 40, borderWidth: 1, marginBottom: 10},
  paragraph1: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: 'blue',
  },
  paragraph2: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});


açıklamalar :

  • ClassComponent yapısında setState methoduna parametre olarak  geçilen bir fonksiyon ile prevState değeri alınabilmektedir.
  • Üstteki örnekte prevState değeri alındıktan sonra price güncellenerek yeni değer state'e kaydedilmiştir.
  • ClassComponent yapısında setState methoduna parametre olarak fonksiyon geçilerek prevState ile birlikte props değeri de alınabilmektedir.
  • const [state, setState] = useState();
    • Hooks yapısında useState ten alınan setState fonksiyonuna parametre olarak fonksiyon geçerek mevcut state değerlerine erişilebilir.
    • Bu sayede üstteki örnekte  eski değere 100 ekleyerek product price  güncellenmektedir.
    • ÖRN: setState(prevState => {return {...prevState, price: prevState.price + 100};});

github(state) : https://github.com/lvntyldz/tutorials/tree/6-react-hooks-prevstate/react-native-hooks-examples

github(projenin tamamı) : https://github.com/lvntyldz/tutorials/tree/master/react-native-hooks-examples

React Native (6) - Hooks ve ClassComponent ile çoklu state object güncelleme

Marhaba,
bu yazımda yine React Native ile multi state kullanımını inceleyeceğiz. Ancak bir önceki yazıdan farklı olarak  burada bir objenin içindeki element güncellenecektir.  Title,ItemCount ve Price değerlerine sahip olan bir product objesi örneklenecektir. title ve price'ta bir değişiklik yapmadan hooks ve ClassComponent ile itemCount değiştirmenin nasıl olacağı paylaşılmaktadır.

ProductItemCount ve ProductItemCountHooks componentleri üzerinde örnekler yapılmıştır. github üzerinden bu componentlerin tamamını inceleyebilirsiniz.

ÖRNEK Product Objesi :
{title: 'iPhone 11',itemCount: 2,price: 1500}

Aşağıdaki adımları takip ederek kendi projenizde uygulayabilirsiniz.

ilk olarak react native ile bir proje oluşturun.
$ react-native init someProject

Terminal üzerinden projenin bulunduğu dizine gidin.
$ cd someProject

kök dizindeki App.js dosyasının içeriğini aşağıdaki şekilde güncelleyin.

import React, {Component, useState} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {AppButton} from 'appComponent/Button';

export default class App extends Component {
  render() {
    return (
      <>
        <ProductItemCount />
        <ProductItemCountHooks />
      </>
    );
  }
}

export class ProductItemCount extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: 'iPhone 11',
      itemCount: 2,
      price: 1500,
    };
  }

  handleItemCountOnPress = () => {
    const itemCountValue = (this.state.itemCount += 1);
    this.setState({itemCount: itemCountValue});
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph2}>
          state : {JSON.stringify(this.state)}
        </Text>
        <AppButton          style={{marginTop: 10}}
          title="increase item count"          onBtnPress={() => 
              this.handleItemCountOnPress()}
        />
      </View>
    );
  }
}

export const ProductItemCountHooks = props => {
  const [state, setState] = useState({
    title: 'iPhone 11',
    itemCount: 2,
    price: 1500,
  });

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph1}>state : {JSON.stringify(state)}</Text>
      <AppButton        style={{marginTop: 10}}
        title="increase item count"        onBtnPress={() =>
            setState({...state, itemCount: state.itemCount + 1})}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    margin: 10,
  },
  input: {height: 40, borderWidth: 1, marginBottom: 10},
  paragraph1: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: 'blue',
  },
  paragraph2: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});



Önemli notlar:
  • ClassComponent örneğinde itemCount değerini güncellemek için react tan gelen ve  class içerisindeki state'i güncellemek amacıyla geliştirilen  setState methodu kullanılmıştır.
  • ClassComponent yapısında state güncellemesi yaparken  setState methoduna güncellenecek element ve bu elementin değeri parametre olarak bir obje içerisinde verilmelidir. ÖRN:   this.setState({itemCount: itemCountValue})
  • Hooks yapısında üstteki örnekte varsayılan state tanımlaması aşağıdaki gibi yapışmıştır : const [state, setState] = useState({title: 'iPhone 11',itemCount: 2, price: 1500})
    •  Buradaki tanıma göre useState ten alınan setState methodunu kullandığınızda state objesi ezilir. Dolayısıyla title ve price değerleri kaybolur.
    •  Bu durumu aşmak için ise önce (...state) tanımıyla mevcutta bulunan state değeri ele alınır daha sonra eldeki state üzerinden itemCount değerinin güncellemesi yapılır. ÖRN:setState({...state, itemCount: state.itemCount + 1})


github(state) : https://github.com/lvntyldz/tutorials/tree/5-react-hooks-multistate-object/react-native-hooks-examples
github(projenin tamamı) : https://github.com/lvntyldz/tutorials/tree/master/react-native-hooks-examples

30 Nisan 2020 Perşembe

React Native (4) - Hooks ve ClassComponent ile stateden değer yazmak ve okumak

Merhaba,
bu yazımda react native ile state'e değer set etmeyi ve bu değeri  stateten okumayı paylaşacağım.
ClassComponent yapısıyla ve Hooks yapısıyla state üzerindeki değeri hem  değiştirerek hem de okuyarak ekrana yazdıracağız.

Aşağıdaki adımları takip ederek sizde projenizde state set/get işlemlerini uygulayabilirsiniz.

ilk olarak react native ile bir proje oluşturun.
$ react-native init someProject

Terminal üzerinden projenin bulunduğu dizine gidin.
$ cd someProject

kök dizindeki App.js dosyasının içeriğini aşağıdaki şekilde güncelleyin.

import React, {Component, useState} from 'react';
import {StyleSheet, Text, TextInput, View} from 'react-native';

export default class App extends Component {
  render() {
    return (
      <View style={{flex: 1}}>
        <Login />
        <LoginHooks />
      </View>
    );
  }
}

export class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>{this.state.username}</Text>
        <TextInput
          style={styles.input}
          onChangeText={text => this.setState({username: text})}
        />
      </View>
    );
  }
}

export const LoginHooks = props => {
  const [username, setUsername] = useState();
  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{username}</Text>
      <TextInput
        style={styles.input}
        onChangeText={text => setUsername(text)}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
    margin: 20,
    backgroundColor: 'skyblue',
  },
  input: {height: 40, borderWidth: 1, marginBottom: 10},
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: 'red',
  },
});


birkaç önemli kısım:

  • useState methodunu React tan import ederek bu method  aracılığıla hooks yapısında state değişikliği yapılır.
  • state'te tutulan değer yine useState methodu aracılığıyla alınır.
  • cons [x,y] = useState(); şeklindeki tanımda x değer y ise bu değeri güncelleyecek fonksiyondur.
  • ClassComponent yapısında ise yine constructor üzerinde state objesi oluşturulur.
  • const {x} = this.state ile ClassComponent'e tutulan state değerlerine erişilir.
  • state teki x değerini ClassComponent yapısında değiştirmek için ise this.setState({x:<VALUE>}) şeklinde  kodlama yapmak gerekir.


github(state) : https://github.com/lvntyldz/tutorials/tree/3-react-hooks-setstate/react-native-hooks-examples

github(projenin tamamı) : https://github.com/lvntyldz/tutorials/tree/master/react-native-hooks-examples


React Native (2) - React Navigation ile Hooks ve ClassComponent ekranlarını gösterme

Merhaba,
bu yazımda react native ile geliştirdiğiniz uygulamalarınıza  react navigation'ı nasıl implemente edeceğinizi paylaşacağım.
React Navigation aracılığıyla ClassComponent ten Hooks ekranına, hooks ekranından da ClassComponent ekranına geçiş yapacağız.

ilk olarak react native ile bir proje oluşturun.
$ react-native init someProject

Terminal üzerinden projenin bulunduğu dizine gidin.
$ cd someProject

react navigation'ı projenize ekleyin
$ npm install @react-navigation/native
$ npm install @react-navigation/stack

react navigation kullanmak için gereken bağımlılıkları ekleyin.
$ npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

60 öncesi react native versiyon kullanıyorsanız aşağıdaki komutla linkleme yapın.
$ react-native link

MAC ve iOS ile çalışıyorsanız aşağıdaki komutla iOS bağımlılıklarını indirin.
$ npx pod-install ios

touch ile src dizininde bir wrapper component oluşturun. Bu componentin içinde diğer componentleri load edeceğiz.
$ touch src/wrapper/index.js

index.js dosyasının içeriğini aşağıdaki şekilde güncelleyin.

import React, {Component} from 'react';
import {StyleSheet, Text, View, Button} from 'react-native';

import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';

const Stack = createStackNavigator();

export default class Wrapper extends Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={Home} />
          <Stack.Screen name="HomeHooks" component={HomeHooks} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

export const HomeHooks = props => {
  return (
    <View>
      <Text style={styles.paragraph}>Hello from HomeHooks</Text>
      <Button
        onPress={() => props.navigation.navigate('Home')}
        title="GoToHome"
      />
    </View>
  );
};

export class Home extends Component {
  render() {
    return (
      <View>
        <Text style={styles.paragraph}>Hello from Home</Text>
        <Button
          onPress={() => this.props.navigation.navigate('HomeHooks')}
          title="GoToHomeHooks"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: 'red',
  },
});


ios simulatorü ile veya android emulatoru ile sonucu gözlemlemek için projeyi çalıştırın.

iOS
$ react-native run-ios

andorid
$ react-native run-android


github: https://github.com/lvntyldz/tutorials/tree/react-navigation-impl/react-native-hooks-examples

4 Ağustos 2016 Perşembe

React native ile Hello World Uygulaması

Merhaba, aşağıdaki adımları takip ederek react native ile ilk IOS uygulamanızı yapabilirsiniz.


1-) node yüklü mü kontrol edin.
node -v 


2-) yüklü değilse  node'u yükleyin
brew install node 


3-) watchman yüklü mü kontrol edin
watchman -v 


4-) watchman'i yükleyin
brew install watchman 


5-) React'ı yükleyin
npm install -g react-native-cli 


6-) Şablon proje oluşturun.
react-native init HelloWorld  



7-) Oluşturduğumuz proje dizinine gidin
cd HelloWorld/ 


8-) index.ios.js dosyasını açın.
vi  index.ios.js 

Bu dosya içerisinde "class HelloWorld extends Component"  satırının olduğu  kısmından başlayarak  oluşturduğumuz  projenin içeriğini görebilir, yine  burayı güncelleyerek ekranda sonucunu görebilirsiniz.


9-) Xcode aracılığıyla bu dosyayı açarak projenin çıktısını emulator üzerinde görebilirsiniz.
 File->Open-> <ProjeDizininine Gidin> -> ios --> buit and run (Derle Ve Çalıştır)