Chapter 3 : Hooks : Heroes Of React !!!
3. React Hooks
a. useState:
This hook makes it simpler to add state management to functional components.
Task: Create a light/dark theme toggle for a webpage. Use useState to manage the current theme.
b. useEffect:
This hook can mimic lifecycle events and handle side effects in functional components.
Task: Fetch a random user data from an API like JSONPlaceholder or Random User Generator and display it on the page. Use the useEffect hook to fetch the data when the component mounts.
c. useContext:
This hook allows functional components to access the context without wrapping them in a Consumer.
Task: Implement a multi-language website (e.g., English and Spanish). Use useContext to manage the current language and display text based on the chosen language.
d. useReducer:
A hook that can be used for state logic that is more complex than useState.
Task: Create a basic counter with increment, decrement, and reset actions. Use useReducer to handle state logic instead of useState.
e. useRef:
Provides a way to access the DOM directly within functional components.
Task: Build an auto-focus input box. When the page loads, the input box should be automatically focused using useRef.
f. useMemo & useCallback:
Hooks used for performance optimization to ensure that computations and functions aren't unnecessarily recreated.
Task: Create a list of numbers and a button that calculates the sum of squared numbers. Ensure that the calculation only recomputes when the list changes using useMemo. Also, ensure that event handlers are memoized using useCallback.
g. Custom Hooks:
Create reusable logic across multiple components.
Task: Design a custom hook useLocalStorage that can get, set, and remove items from local storage.
h. useContext + useReducer:
Combining these two hooks can mimic a lot of Redux's functionality for state management.
Task: Construct a basic shopping cart. Use useContext to create a global state accessible across components. Utilize useReducer to manage adding items to the cart, removing them, and clearing the cart.
Project: Note-taking App:
- Allow users to create, edit, and delete notes.
- Use
useStateoruseReducerto manage the state of notes. - Use
useEffectto persist notes in local storage so they remain after a page refresh. - If possible, allow for searching and categorizing notes, using additional hooks as required.
Through these tasks and projects, you'll gain hands-on experience with React Hooks, which will empower you to write more readable, maintainable, and functional React code.