- 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());
- can be used to hold intermediate components, for our case maybe getMainImages() in gallery.
- Expects a second argument, this argument is equality checker function, you can use this to override default prop equality check.
- Do not overuse it, avoid if you aren't getting significant results
- 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
- 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'
@trishulgoel
Thank you!