X
X
xZand2021-06-02 20:40:00
React
xZand, 2021-06-02 20:40:00

Should you use hooks like useState when you're already managing state with Redux?

I ask you not to throw stones strongly, I'm just learning React, and so far one idea is not clear.

I create a pet project:

picture
60b7bfd0cd6c9661994353.png


Now the tushka distributes the state by props through the root component Home -> props.
Everything was fine until the need came to pass the state from the root Home component to the NewToDo component, which is located in another Route.
Code

const Router = (props) => {
  return (
    <div>
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/new" component={NewToDo} />>
          <Route component={NotFound} />
        </Switch>
      </BrowserRouter>
    </div>
  );
};


I created a separate branch in the git, and started digging redux, and at the very first moment I saw that, in principle, you can not use the useState hook when redux gives its useDispatch()and useSelector(), which control the global state. Question : does the useState hook make sense if you are already using the redux store?

And the second question:
Now the root component contains a function:

const [formatData, setFormatData] = useState({});
useEffect(() => {
    const dateKeys = ["weekday", "day", "month", "year"];
    (function () {
      const ruDate = new Intl.DateTimeFormat("ru", { ------ получаю дату
        day: "2-digit",
        month: "long",
        year: "numeric",
        weekday: "long",
      })
        .format(new Date())
        .replace(/,/, "")                ----//убираю и меняю символы
        .replace(/в/, "В")
        .replace(/с/, "С")
        .replace(/\sг./, "")
        .split(" ");                      --------  создаю массив

      const result = Object.assign(                           ----- привожу массив к виду объект: {ключ: свойство}
        ...dateKeys.map((k, i) => ({ [k]: ruDate[i] }))
      );
      setFormatData(result);
    })();
  }, []);

which gives a template string with a formatted date, and then I pass it by props to the component. Question:
Is this sausage a shit code? And if so, how can it be reduced?
.replace(/,/, "")                ----//убираю и меняю символы
        .replace(/в/, "В")
        .replace(/с/, "С")
        .replace(/\sг./, "")

The second question:
It is this function (the object that I then store in useState) that I must pass to another route component. Where should this function be stored? In the store and put it in the store as an object by assignment?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Anton, 2021-06-02
@karminski

In a nutshell, redux is for the global state of the entire application (for example, storing table data), and hooks for the state of individual components (such as tabs). But this is not a panacea. Personally, I have an application that only uses state hooks.

N
n1ksON, 2021-06-02
@n1ksON

Don't use props to push dispatch and store from redux. For this, as you correctly noted, there is useSelector and useDispatch.
1. useState is very necessary despite the use of redux. For example, your site displays a notification when you click on a button. Why push notification display status in redux? Redux, as rightly noted, is like a global store. There is no need for this, for the display status (true / false) it is enough to use useState inside the component.
2. The question was not quite correctly formulated.
If your function is used only in a specific component, store it in it.
If a function is used in several components of the same level, move the function to a higher level where these components are imported.
If a function is often used in different places, put it in a separate file (utils) and import it into the necessary components.

Question: Is this sausage a shit code?

It's not clear what she decides. Perhaps you can write a little more beautifully or even on regular expressions. The main thing is to solve the necessary task

M
Mikhail Derkach, 2021-06-10
@skeevy

1. Redux / any other state manager for global states and storing a large amount of data
2. useState - for the state of the component, for example, switching the flag by which the active class is added for the element
I use this approach when there is a Redux / MobX / Recoli application /etc. + Dan Abramov himself spoke about this approach. (HolyJS 2020)

A
Alexey, 2021-06-11
@slide13

Everyone has already said about redux, often there is a need to use useState in the presence of redux and this is normal.
About replace . Because you can pass a function to replace for a string as a second parameter, then here you can clearly use this:
make an object where the key would be a substring from the match, and the value would be what it needs to be replaced with and then, by coincidence, substitute the desired value from the object, approximately So:

let matches = {
  ",": "",
  "в": "В",
  "с": "С",
  " г.": ""
}

.replace(/с|в|\sг./g, (match) => matches[match])

But from what I see, it's easier to take the dayjs library and calmly format dates, 2KB is hardly worth the time to write your own date formatting implementations.
Further, of course, you don't need to store functions in the editor. Various extras. it is better to put functions in a separate folder and break them down by type, for example, for working with dates, for formatting numbers, etc. and import the desired components directly from there.
This is useful because no one knows when and to whom it will come in handy again, and even more so if it is a big project. Having written it somewhere in your components, they may not find it and create a copy somewhere else. It will also have to be tested, it is easier to import utilities for tests from one place than to search by components, and the utilities will still have to be tested separately from the ui.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question