I'm using hooks in my react project.
I have written a function to manage the state in hooks.
but I don't know if it is Optimal.
This is my function:
mapStateToDOM.js
import {useState} from 'react';
const mspStateToDOM = (initialState, state) => {
Object.keys(initialState).map(item => {
let [current, setCurrent] = useState(initialState[item]);
state[item] = {get: () => current, set: setCurrent};
});
};
export default mspStateToDOM;
And with it, I can get a variable from state by using state.varName.get()
And I can change a variable by using state.varName.set(SOME_VALUE)
Here is my code:
import React from 'react';
import mspStateToDOM from '../config/mapStateToDOM/mapStateToDOM';
const Counter = () => {
const state = {};
const initialState = {
count: 5,
count2: 6
};
mspStateToDOM(initialState, state);
return (
<div>
<p>You clicked {state.count.get()} times</p>
<button
onClick={() => {
state.count.set(state.count.get() + 1);
}}>
Click Me!
</button>
</div>
)
};
export default Counter;
This makes the code much cleaner, readable, and easier to use. and I don't have to define a setter for each variable and use 'useState' many times in my code.
but I don't know if it is optimal. Is it?
You can't use hooks inside a loop\callback as stated in Rules of Hooks.
Therefore, such code is error-prone, the only reason you don't get a warning as the linter can't guess it's a custom hook.
Try adding use
prefix to your custom hook name and see the warning:
React Hook
useState
cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function. (react-hooks/rules-of-hooks)
const useMapStateToProps = (initialState, state) => {
Object.keys(initialState).map(item => {
let [current, setCurrent] = useState(initialState[item]);
state[item] = { get: () => current, set: setCurrent };
});
};
Moreover, there are few bugs in this snippet:
state
andinitialState
will re-assign on every render.- Use of
map
without a return value. - Rules of Hooks as stated above.
- Not a bug but in those snippets, it seems you trying to use OOP approach which comes from classes, in a function, while hooks motivate you for functional programming.
- Refer to Using Custom Hooks