[29-30] useEffect, useReducer and more
Weeks 29-30. I'm still needed to cover some topics about HTML/CSS but because of bad time management I couldn't find time for that, but it's OK since React still is my main goal to learn.
The expenses app is ready.
Styles in React, styled-components, CSS modules.
Self-work. Form and list with validation and alert in a reusable modal window. Fixed dubious code while watching the author's solution.
Fragments, portals, refs.
Side effects. useEffect hook.
useEffect hook cheat sheet:
- useEffect(() =>) - Runs only the first time when a component mounts, and each time when the state update. At the end of each rendering cycle.
- useEffect(() =>, []) - As in the above, after the first rendering cycle, but further, only after both are true: rerendering and dependency ([]) change.
- useEffect(() =>{return ()=>{}}, []) - cleanup function runs before each start of parent function, BUT not the first time. And it also runs after the component is unmounted from DOM.
- useEffect(() =>{return ()=>{}}) - during unmount only
useReducer, useContext and forward refs
useReducer summary:
const [state, dispatchFn] = useReducer(reducerFn, initialState, initFn);
state - state snapshot
dispatchFn - function for state snapshot update (forwards action which will be available in the first argument of reducerFn).
reducerFn - a function that triggers automatically, when action passed through dispatchFn. Receives state snapshot as a first argument and trigger action as a second one. Should return new, updated state.
initialState - initial state of the state snapshot.
initFn - function for more complex configuring of the initial state.
- React context limitations:
- Doesn't fit for frequent changes
- Is not a substitute for all props chains.
React meals app finished.
React behind the scenes:
Component - re-evaluated each time when props, state or context changes and a function of component re-runs.
DOM - updates only in those places where it should be updated, based on the difference between the current and last state.
If a component is re-evaluated (re-runs), thus all its children would be re-evaluated. But, it doesn't mean that there would be changes in DOM necessarily.