useHooks

useState

Simple state hook

Initialize state and get setState function

- Initial value can be lazyloaded(function overloading)
- set[hook] can have previous state
- always use previous state to update state in async opeartions, for example: counters

const initialValue = someexpecnsiveCalculation();
const [val, setVal] = useState(initialValue);

// lazy initialization
const [val, setVal] = useState(() => someexpecnsiveCalculation());

useMemo

Caches the return of a function

Used for caching heavy/complex calculations, given same arguments

- can be used to hold intermediate components, for our case maybe getMainImages() in gallery.

React.memo

Memoize whole component

Given props do not change, it prevents component from rerender

- Expects a second argument, this argument is equality checker function, you can use this to override default prop equality check.

useCallback

Caches the functions to prevent creation of new instances on subsequent re-render. Example: adding listeners.

- Do not overuse it, avoid if you aren't getting significant results

useEffect

- Applies given effect based on condition on re-renders.

- expects second argument as array of dependencies.

- Executes after rendering.

- Keep the dependencies as less as possible.
- Do not shy to use multiple useEffects in a component.
- Separation of concerns - do not club different logics in same hook.
- This can easily side effect in re-running effect, the deps are matched with shallow comparison.
        Avoid passing objects.
        Avoid passing functions.
        Best choices are number/string/boolean

 

- Passing a referenced object(may be object return of useSelector?)
- referenced functions (dispatch from useDispatch?)
- If its really needed to pass a function, prefer following way.

 

 

// Usecallback so that the function remains same in subsequent rerenders
const initFetch = useCallback(() => {
  dispatch(fetchPosts());
}, [dispatch]);

useEffect(() => {
    initFetch();
}, [initFetch]);
// since function is not recreated shallow comparision would work here

Permissible deps

useSelector

Used to get data from redux store.

The return value of `selector` function is return value of useSelector().

Selector function gets redux state as the argument.

- Do not shy to use multiple useselectors.
- Make it as granular as possible.

Note -> 
If you need to destructure value from useSelector, consider using more useSelector

Multiple selectors will not trigger multiple renders the update call is batched.

```

When an action is dispatched, useSelector() will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render.

```

```

useSelector() uses strict === reference equality checks by default, not shallow equality

```

  • const error = useSelector(state => state.productdetails.error);
    const response = useSelector(state => state.productdetails.data);
    const data = error ? null : data;
const error = useSelector(state => state.productdetails.error);
const response = useSelector(state => state.productdetails.data);
const data = error ? null : data;

DON'T

DO

const testObj = useSelector((state) => {
  if (!state.productdetails.error) {
    return {
      error: false,

      data: state.productdetails.data,
    };
  } else {
    return {
      error: true,

      data: null,
    };
  }
});

If you really need to put logic in the selector function, then an  `equalityFunction` can be passed as second argument for `useSelector`.

 

useSelector(selectorFunction, equalityFunction)

 

Most commonly used one is `shallowEqual` can be imported from 'react-redux'

useDiscuss

@trishulgoel

Thank you!

Made with Slides.com