Hooks 1: useState and useReducer


useState


const [a,setA] = useState(initA);
# update value 
setA(newA); # for value like string, int, float, etc.
setA(prev => {return {...prev,newKey}}) # for list or dict
setA(prev => {return [...prev,newVal]})
    

useReducer

flowchart LR subgraph "store" A[actions.jsx] B[index.js] C[states.jsx] end A --> B; C --> B; B --> D[main.jsx];

states.jsx , defining initial value of all parameters.


export const initState = {a:initA, b:initB}
    

actions.jsx , defining how param is updated and modified.


export const reducer = (state,action) => {
    switch (action.type){
        case 'list':
            return {...state,[action.key]:action.value};
        case 'object':
            return {...state,[action.key]:action.value};
        case 'value':
            return {...state,[action.key]:action.value};
        default:
            return state
    }
}
    

index.js


export { initState } from './states'
export { reducer } from './actions'
    

main.js


import {initState,reducer} from './store'
const [{a,b},dispatch] = useReducer(reducer,initState)
dispatch({type:'value',key:'a',value:newA})
dispatch({type:'value',key:'b',value:newB})
    

References