Por que a veces React / Redux en su estado actual me da escalofríos

React ha existido el tiempo suficiente para que los cambios importantes en esta biblioteca no se sientan por la temperatura de calentar las sillas del desarrollador en las frías noches de invierno (no agradezco el truco de la vida). Pero Facebook hizo un movimiento de caballero y en un momento lanzó no una versión mayor, sino una menor y, por lo tanto, se liberó de la responsabilidad por la inestabilidad de los millones de repositorios ya existentes, como ya entendió, hablaré sobre la versión 16.8.0, y como casi nunca usamos React sin Redux en repositorios de producción, entonces te lo contaré. 





React. “” 16.8.0, - Facebook , , , . Statefull Components Stateless Components e functional Components useState, useCallback, useEffect etc. useContext.





, 4 , -:





  • - Fine





  • - Excellent





  • - Splendid





  •   - Lifecycle - - , clean-up , - Amazing (c)





, (. ):





import React, { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}
      
      



( ):





// useFriednStatus.js

import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import * as actions from 'actions';
import { getLoggedInUserSelector } from 'selectors';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}

// useBestFriendNotifier.js

import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import * as actions from 'actions';
import { getLoggedInUserSelector } from 'selectors';

function useBestFriendNotifier(currentUserId) {
    const loggedInUser = useSelector(getLoggedInUserSelector);

    const isBestFriendOnline = useFriendStatus(loggedInUser.bestFriendId);
    const dispatch = useDispatch();

    const notifyMeAboutBestFriendActivity = React.useCallback(() => {
        dispatch(actions.notify(isBestFriendOnline));
    }, [isBestFriendOnline]);

    return notifyAboutBestFriendActivity;
}

// Notification.jsx

import { bestFriendOnlineSelector } from 'selectors';

function Notification(({ id }) => {
    const notifier = useBestFriendNotifier(id);
    const isOnline = useSelector(bestFriendOnlineSelector);

    return (
        <p>Your Best friend is { isOnline ? 'Online' : 'Offline' }</p>
    );
});
      
      



, , , , , Store .





, . , , , , : , , :





Please, do not use more then one level nesting of custom hooks 





Stateful Componetns Stateless Componetns, function Components (, , Stateful) function Components, .





We don’t recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you’d like.





, , , , , , , , , , .





, , - , , - , - . - , , , - Skrum , .





. - , , .



redux-thunk, - dispatch() dispatch(), dispatch() action dispatch() action with type ... payload, dispatch() TypeScript :





function App(() => {
    dispatch(actions.init());
});

// actions.ts

export const init = (): ThunkAction<void, RootState, void, AppAction>  =>  {
    return async (dispatch, getState) => {
        try {
            const user = await getUser();
            if (!user) {
                dispatch(setNotLoggedInUserState());
            }

            dispatch(setLoggedInUserState(user));
        } catch (e) {
            dispatch(showErrorModal);
        }
    };
}

const setNotLoggedInUserState =  (): ThunkAction<void, RootState, void, AppAction> => {
    return async (dispatch, getState) => {
        dispatch(setDefaults());
        dispatch(showLoginModal());
    };
}

const setLoggedInUserState = (user): ThunkAction<void, RootState, void, AppAction> => {
    return async (dispatch, getState) => {
        dispatch(wellcomeBackModal(user.name));
    };
}

// ...
      
      







Este es solo un razonamiento sobre el hecho de que no siempre está de moda === es lo mejor, y quizás valdría la pena dar paso a un enfoque más comprensible si, de todos modos, no hay beneficio en el rendimiento de la aplicación. Sin embargo, los propios desarrolladores de Facebook en algunos artículos admiten que a menudo pueden abandonar código comprensible en nombre de minimizar cadenas, por ejemplo.








All Articles