Current Size:
Chakra BreakPoints
base0px
sm480px
md768px
lg992px
xl1280px
2xl1536px
Current Height:Width
widthpx
heightpx

Subjects

React.js State Management Pattern 2023

Date Created: 2022/10/28

Last Update: 2023/07/08

#reactjs #cheatsheet #reference #notes #state-management

Context API

Pattern Two

Pattern pulled from

recat tracked

import React, { ReactNode, createContext, useState, useContext } from 'react';
const initialState = {
count: 0,
text: 'hello',
};
const useMyState = () => useState(initialState);
const MyContext = createContext<ReturnType<typeof useMyState> | null>(null);
export const useSharedState = () => {
const value = useContext(MyContext);
if (value === null) throw new Error('Please add SharedStateProvider');
return value;
};
export const SharedStateProvider = ({ children }: { children: ReactNode }) => (
<MyContext.Provider value={useMyState()}>{children}</MyContext.Provider>
);
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { SharedStateProvider } from './store';
import Counter from './Counter';
import TextBox from './TextBox';
const App = () => (
<SharedStateProvider>
<div className="App">
<header className="App-header">
<Counter />
<TextBox />
<img src={logo} className="App-logo" alt="logo" />
</header>
</div>
</SharedStateProvider>
);
export default App;

Pattern One

import React, {createContext, useContext, useState} from 'react'
export const FooContext = createContext();
export const FooProvider = ({children}) => {
const { foo, setFoo} = usState()
return (
<FooContext.Provider value={{foo, setFoo}}>
{children}
</FooContext.Provider>
)
}
export const useFooValue = () => useContext(FooContext)
import React from 'react'
import ReactDOM from 'react-dom'
import * as serviceWorker from './serviceWorker'
import {
FooProvider,
} from './foo-context.js'
Const App = () => { return (
<div>
<h1>Context Pattern 2020</h1>
</div>
}
ReactDOM.render(
<React.StrictMode>
<FooProvider>
<App />
</FooProvider>
</React.StrictMode>,
document.getElementById('root')
)

Jotai

AtomWithReducer

Reference

is an extension of the context API handling rerenders in a more efficient way only triggering re-renders if the accessed property is changed.

takes an atomic approach to global React state management with a model inspired by Recoil.

More Notes

All Notes
HomeProjects

Links

Home Articles Notes Projects About Style Guide Site Credits

Contact

 [email protected]

Location

🌎 Earth