setCount(count + 1) --> Wrong way
Problem of using above approach https://codesandbox.io/s/gracious-curran-8jlk5
setCount(count => count + 1) --> Correct way
https://kentcdodds.com/blog/use-state-lazy-initialization-and-function-updates
So if you are a heavy task to get intial value for useState then using function that returns heavy task output to that useState. For Example, Let's say your inital value to useState is
JSON.parse(localStorage.getItem('userData'))
we know that getting value from localStorage and parsing is a heavy task.
const [userData, setUserData] = useState(JSON.parse(localStorage.getItem('userData'))) --> Inefficient Way
So what happens here is that when our component re-renders by other reasons then useState is gonna do the same getting item from localStorage and parsing which is ineffificent
cosnt [userData, setUserData] = useState(() => JSON.parse(localStorage.getItem('userData'))) --> Efficient Way
So by providing function that does the heavy lifting. React will only call the function when it needs the initial value (which is when the component is initially rendered) and after that it does not call the function to set inital value on every re-renders.
As we know react doesnot allow us to directly interact with DOM, although we might use something like
<h1>Title<h1>
but later it is converted to
React.createElement('h1',{children: 'Title'})
.
So inorder to access DOM we need to wait for react to finish
React.render(<App />,document.getElementById('div'))
and then after first render we can access DOM using useRef hook
const inputRef = useRef()
React.useEffect(() => {
const inputNode = inputRef.current
// do something with inputNode
},[])
<input ref={inputRef} />
Using a status enum (or even better: a state machine) will help your app stay bug free.
status: 'started'
status: 'pending'
status: 'idle'
status: 'resolved'
status: 'rejected'
You never know what error might occur so rather than writing your own error catcher we can wrap component with ErrorBoudnary component to prevent from distrupting the whole site on error.
https://reactjs.org/docs/error-boundaries.html
Simple Error boundary implementation
https://codepen.io/gaearon/pen/wqvxGa?editors=0010
Also we have an opensource npm package called *react-error-boundary