ReactJs Components
Why hooks
-
why hooks
- simplify code
- previously for new comers to react, there was a need to learn what this means in javascript making the learning experience harder
- make it more performant
- simplify code
-
useState
- set as a prefix is a convention
-
useEffect
- it is a side effect (pure vs impure functions)
rules
- call hooks only from react function
- call hooks at the top level
- you can call multiple state or effects
- make multiple calls in sequence - [fetch data](https://react.dev/reference/react/useEffect#fetching-data-with-effects)
- used to make server request - advanced hooks
- useReducer
- The useReducer hook is best used on more complex data, specifically, arrays or objects.
- useRef
- [custom hooks](https://react.dev/learn/reusing-logic-with-custom-hooks)
Examples
-
useSyncExternalStore
- react hook syncs the current state based on an external source
- it was created based on client/server communication
-
useHooks – The React Hooks Library
- a premade hooks library with different usages
-
https://youtu.be/Ck-e3hd3pKw?t=4002 14 - useEffect reactathon 2022
- the key message here is to use effects in event handlers
- notes:
- useEffect is not for effects
- useEffect is an infinite loop by default
- useEffect is not a state setter
- imperative
- declarative
- useffect is for synchronization
- effects go in event handlers
-
Reusing Logic with Custom Hooks – React
- repetitive logic
-
prove to the linter that it don’t need to be a dependency
- use effect patterns
- New client-side hooks coming to React 19