React hooks state Management

mskashef :


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?

Dennis Vash :

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:

  1. state and initialState will re-assign on every render.
  2. Use of map without a return value.
  3. Rules of Hooks as stated above.
  4. 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.

Edit gracious-bassi-1q3s6

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=220492&siteId=1