January 26, 2022

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

Redux Who? Handle your own state instead


State management libraries for React are a dime a dozen. Redux. Recoil. MobX. Choosing one is a hard task for even the most experienced developers – but have you ever considered skipping the choice altogether?

Some apps need advanced state management. They really do! When you’re handling hundreds of different variables that change as a reaction to other state values, things will definitely be easier to scale when you’re using a library like Recoil. However, I’m willing to venture that your app doesn’t need it.

In this article, I will present how you can handle state, even at scale, by co-locating it and keeping it simple.

The basics of state handling

With all the Reduxes of the world, it’s easy to forget that React ships with its own state management system! Let’s look at how it looks.

1const [count, setCount] = React.useState(0);

If you need to handle any kind of value that changes over time, you add a call to the useState hook. This works great for simple values that change one at a time.

Memoize instead

Some data doesn’t even need to live in state! Take this example:

1const [filter, setFilter] = React.useState('none');

2const [filteredItems, setFilteredItems] = React.useState(props.items);

3

4function onFilterChange(newFilter) {

5 setFilter(newFilter);

6 setFilteredItems(

7 props.items.filter(item => item.someProperty === newFilter)

8 );

9}

Here, there’s no real reason for keeping the filtered items in state! Instead, we could memoize the filtering, and only recompute the new filtered items whenever the filter (or items to filter) changes.

1const [filter, setFilter] = React.useState('none');

2const filteredItems = React.useMemo(() =>

3 items.filter(item => item.someProperty === newFilter),

4 [props.items, filter]

5);

6function onFilterChange(newFilter) {

7 setFilter(newFilter);

8}

Use a reducer

If you have some more advanced state, you can also use the more flexible useReducer hook!

1const [request, dispatch] = React.useReducer((state, action) => {

2 switch (action.type) {

3 case 'loading': return { state: 'loading' };

4 case 'success: return { state: 'success', data: action.data };

5 case 'error': return { state: 'error', error: action.error };

6 case 'reset': return { state: 'idle' };

7 default: throw new Error(`Unknown action ${action.type}`);

8 }

9}, { state: 'idle' });

You can do the same with several useState calls, but when several changes happen at the same time, I tend to use useReducer instead. Luckily, that doesn’t happen too often.

Share state across components

Now, if you need this state in several places, you need to “lift it up” to the first common ancestor component.

If there aren’t lots of component layers between them, you can simply pass down the value and the updater function as props.

1const CommonAncestor = () => {

2 const [filter, setFilter] = React.useState('none');

3 return (

4 <div>

5 <FilterSelector filter={filter} setFilter={setFilter} />

6 <FilteredItems filter={filter} />

7 </div>

8 );

9};

Use contexts when appropriate.

If there are tons of layers between the first common ancestor and your components, or if you’re creating reusable, generic components where you can’t apply props directly, you want to create a context.

In the case you need to create context, a Provider component and a hook to consume the context need to be added.

1const FilterContext = React.createContext();

2const FilterProvider = (props) => {

3 const [filter, setFilter] = React.useState('none');

4 return (

5 <FilterContext.Provider value={{ filter, setFilter }} {...props} />

6 );

7};

8const useFilter = () => {

9 const context = React.useContext(FilterContext);

10 if (!context) {

11 throw new Error("Wrap your component in a FilterProvider");

12 }

13 return context;

14};

Now, we can change your common ancestor component to look like this:

1const CommonAncestor = () => {

2 return (

3 <FilterProvider>

4 <FilterSelector />

5 <FilteredItems />

6 </FilterProvider>

7 );

8};

We have moved all the filter related code into the FilterProvider, and remove all props passed to the FilterSelector and FilteredItems. The latter two can now look like this:

1const FilterSelector = () => {

2 const { filter, setFilter } = useFilter();

3 return (...);

4};

5

6const FilteredItems = () => {

7 const { filter } = useFilter();

8 const items = getItemsSomehow();

9 const filteredItems = React.useMemo(

10 () => items.filter(item => item.someProperty === filter),

11 [filter, items]

12 );

13

14 return (...)

15};

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue.
It’s like having your browser’s inspector open while looking over your user’s shoulder.
OpenReplay is the only open-source alternative currently available.

Happy debugging, for modern frontend teams – Start monitoring your web app for free.

Most state isn’t global

A mistake I see a lot of people doing in the wild, is creating a lot of global contexts when they don’t really need it. It’s an easy mistake to make – especially if you’re used to the Redux way of thinking. It’s kind of annoying though, because you end up with this huge nesting and I’m here to tell you that you most likely don’t need it.

Server cache isn’t state.

In my opinion, saving – or caching – data from your server isn’t state. It’s cache. Therefore, I think you should use some kind of data fetching hook (like useSWR or react-query) that handles all of that for you. You could write your own, of course, and a very simple version of that would look something like this:

1const cache = {};

2const useFetch = (key, fetcher) => {

3 const [request, dispatch] = React.useReducer(

4 requestReducerFromEarlier,

5 { state: 'idle' },

6 );

7 const goFetch = async () => {

8 try {

9 dispatch({ type: 'loading' });

10 const result = await fetcher(key);

11 dispatch({ type: 'success', data: result });

12 cache[key] = result;

13 } catch (e) {

14 dispatch({ type: 'error', error: e });

15 }

16 };

17 if (cache[key]) {

18 goFetch();

19 return { data: cache[key], ...request };

20 }

21 return request;

22}

With this (or, more likely, a library that does a better job at the same), you can remove most of these global contexts in a single swoop, and co-locate the data requirements with where it’s used.

Co-locate when you can

And speaking of – make sure to co-locate all state with where its used. Avoid using global contexts whenever you can. When you do this, you make sure you’ll delete all related state when you delete some feature. It’s easier to find, and there’s much less magic to understand.

In conclusion

Handle your own state when possible. That’s it, that’s the conclusion.
Also, stop defaulting to use hard-to-learn state management libraries, and use the tools React provides out of the box.



Source link