[React] For sync code initialise state, you don't need useEffect
Here is a component which doesn't need to use useEffect
export function LocalTodos() {
const [todos, setTodos] = useState([])
useEffect(() => {
const storedTodos = localStorage.getItem('todos')
if (storedTodos) {
setTodos(JSON.parse(storedTodos))
}
}, []);
return (
...
)
}
Because using localStorage.getItem('todos')
which is sync API. so you can actually do:
export function LocalTodos() {
const storedTodos = localStorage.getItem('todos');
const [todos, setTodos] = useState(JSON.parse(storedTodos) || [])
return (
...
)
}
This tip only apply for SYNC code, doesnt' apply to AYNC code.