[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.

posted @ 2024-04-08 14:54  Zhentiw  阅读(1)  评论(0编辑  收藏  举报