Flutter hooks – useMemoized() | A brief overview

useMemoized :

In this blog we will be dealing with the usage of caching concept in flutter apps using flutter hooks, when every there is any complex object than we can cache it and use it for later use.

This process of caching is achieved by useMemoized which will improved app performance and speed.Also we make use of flutter hooks to improve app’s performance.

The work of useMemoized is to make cache of the complex objects and use them whenever necessary as like the output is same everytime so we need to waste time in processing.

In this example we have consider a time period and were waiting for a certain time to make the work done as a simple example so that you can understand how the processing is delayed for sometime in real scenario’s.

 

 

pubspec.yaml :

Add flutter hooks dependency to pubspec file so that we can enable cache using useMemoized.Make sure you add the latest version of plugin.

dependencies:
  flutter:
    sdk: flutter

  flutter_hooks: ^0.18.3

 

main.dart :

Let’s get started with our void main where we specify the class using run app such that our program starts here and goes on.

Here we are trying to cache the fetchData function and use it multiple times avoiding the delay we face.

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

void main()
  runApp(MyApp());


class MyApp extends StatelessWidget 
  const MyApp(Key? key) : super(key: key);

  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("flutter Hooks"),
        ),
        body: Hook()
      ),
    );
  


class Hook extends HookWidget 
  const Hook(Key? key) : super(key: key);

  @override
  Widget build(BuildContext context) 

    final count = useState(0);
    count.value++;

    Future<String> fetchData() async
      await Future.delayed(Duration(seconds: 1));
      return "Hello World $count.value";
    

    final future = useMemoized(fetchData, []);
    final snapshot = useFuture(future);

    return Center(
      child: snapshot.hasData ? Text("$snapshot.data")
          : CircularProgressIndicator(),
    );
  





 

If you have any queries in this concept of useMemoized let us know in the comment section below.Do like and share us if you like this tutorial for more interesting updates coming up.