---
# System prepended metadata

title: React Test Part 2 - Hooks
tags: [tests]

---

###### tags: `tests`
# React Test Part 2 - Hooks

1. Optimize the following list’s render. Which are the (at least) 2 things missing in the current implementation and how do they affect the rendering process ? Flow typing added just to describe `items` format, you're free to use plain JS in the solution.

```
// @flow

type Item {
  id: string,
  title: string,
}

type AppProps {
  items: $ReadOnlyArray<Item>,
}
 
const App = (props: AppProps) => {
 const renderItem = (item: Item, index: number) => (
   <li key={index} onClick={() => console.log(item)}>
     {item.title}
   </li>
 )
 
 return (
   <ul>
     {props.items.map(renderItem)}
   </ul>
 );
}
```

2. The following hook was designed to debounce value changes. It should change output value each time the source value stops changing (with an ms time gap, e.g. if no changes during this amount of milliseconds - it returns the latest value). 
  - What’s wrong with its implementation ? 
  - Which issues we could have with it and why ? 
  - Rewrite this hook and provide the working solution which doesn’t violate the hooks rules.

``` 
import { useEffect, useState } from 'react';
import { debounce } from 'lodash'
 
const useDebouncedValue = (value, ms = 100) => {
 const [debounced, setDebounced] = useState(value)
 
 useEffect(debounce(() => {
   setDebounced(value)
 }, ms), [ms, setDebounced, value])
 
 return debounced
}
```

## Bugfix
- The following component should display a notification each time when the user switches to another tab / application. The notification can be dismissed by clicking the button. 
- It is also a part of react-native-web application so it should work in the browser, on iOS and on Android.

```
import React from 'react'
import { StyleSheet, Text } from 'react-native'

const Test = () => {
  const [notify, setNotify] = useState(false)

  const toggleNotify = useCallback(() => {
    setNotify(!notify)
  }, [])

  useEffect(() => {
    window.addEventListener("blur", (e) => {
      toggleNotify()
    })
  })

  return (
    <View style={styles.container}>
      {notify && (
        <View style={styles.notification}>
        <Text style={styles.label}>Don't forgot to save the changes Your did</Text>
        <Button style={styles.button} title="Dismiss"onClick={onDismiss} />
        </View>
      )}
      <Text style={styles.label}>Some UI would be here...</Text>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {},
  label: {},
  notifiction: {},
  button: {}
})

export default Test
```

1. Answer the following questions
    1. Would the component work on all platforms?
    2. Why does the button click doesn’t have any effect? And how to fix it?
    3. What are 2 things missing in useEffect to make codemore robust, correct, performant?
    4. What else could be improved and/or simplified in thecode?
2. fix the code according to your above answers