Skip to content

Instantly share code, notes, and snippets.

@Megajjks
Last active August 26, 2020 19:13
Show Gist options
  • Save Megajjks/4d565d2e0126fdcffe7385c097974a04 to your computer and use it in GitHub Desktop.
Save Megajjks/4d565d2e0126fdcffe7385c097974a04 to your computer and use it in GitHub Desktop.
boilerplate of Create component with useReduce
export const actions = {
//the key value will be written calmalcase : The value will be written uppercase
nameAction: "NAME_ACTION",
nameAction2: "NAME_ACTION2"
//...more actions
}
//πŸ‘† In this document the actions of the reducers are written πŸ‘†
import React, { useReducer } from "react" //implement the useReducer
import { actions } from "./actions" //you can change the path depending where is it located the file actions
import { initialState } from "./constants" //you can change the path depending where is it located the file actions
import { reducer } from "./reducer" //you can change the path depending where is it located the file actions
export const Component = () =>{
//implement the reducer
const [state, dispatch] = useReducer(reducer,initialState)
//reducer refers to the file and the changes that will be executed according to the actions
//initialState refers to the file where is the state that will be changing (mutating)
//you can dispatch to change the state depending of the action create
dispatch({
type:actions.nameAction,
payload:"data to send depending of type data"
})
//type define the action you want to call **remember this action change the state in the reducer
//payload define the data of send **rember the data type musst be the same as what you define in the initialState
}
export const initialState = {
state1:"",
state2:[],
//... more state
}
/*πŸ‘† In this document the state that will be used is written together with the values
that will contain it, which can contain any type of data πŸ‘†
Remember use πŸ‘€ camelcase πŸ‘€ to define the name of value */
//import the actions
import { actions } from "./actions" //you can change the path depending where is it located the file actions
export const reducer = (state, action) =>{
switch (action.type) {
case actions.nameAction:
return {
...state,
state1: "hello",
state2: action.payload
};
case actions.nameAction2:
return {
...state,
state1: "hey",
state2: ["w","o","r","l","d"]
};
//more case depending of actions...
default:
return state;
}
/* πŸ‘† In this document the updates of the state are declared depending on the action πŸ‘†
πŸ‘€ the parameter payload is the data of you send in the implementation πŸ‘€*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment