How to implement observable watching for value in React Context - javascript

Let's say I'm having a Parent Component providing a Context which is a Store Object. For simplicity lets say this Store has a value and a function to update this value
class Store {
// value
// function updateValue() {}
}
const Parent = () => {
const [rerender, setRerender] = useState(false);
const ctx = new Store();
return (
<SomeContext.Provider value={ctx}>
<Children1 />
<Children2 />
.... // and alot of component here
</SomeContext.Provider>
);
};
const Children1 = () => {
const ctx = useContext(SomeContext);
return (<div>{ctx.value}</div>)
}
const Children2 = () => {
const ctx = useContext(SomeContext);
const onClickBtn = () => {ctx.updateValue('update')}
return (<button onClick={onClickBtn}>Update Value </button>)
}
So basically Children1 will display the value, and in Children2 component, there is a button to update the value.
So my problem right now is when Children2 updates the Store value, Children1 is not rerendered. to reflect the new value.
One solution on stack overflow is here. The idea is to create a state in Parent and use it to pass the context to childrens. This will help to rerender Children1 because Parent is rerendered.
However, I dont want Parent to rerender because in Parent there is a lot of other components. I only want Children1 to rerender.
So is there any solution on how to solve this ? Should I use RxJS to do reative programming or should I change something in the code? Thanks

You can use context like redux lib, like below
This easy to use and later if you want to move to redux you change only the store file and the entire state management thing will be moved to redux or any other lib.
Running example:
https://stackblitz.com/edit/reactjs-usecontext-usereducer-state-management
Article: https://rsharma0011.medium.com/state-management-with-react-hooks-and-context-api-2968a5cf5c83
Reducers.js
import { combineReducers } from "./Store";
const countReducer = (state = { count: 0 }, action) => {
switch (action.type) {
case "INCREMENT":
return { ...state, count: state.count + 1 };
case "DECREMENT":
return { ...state, count: state.count - 1 };
default:
return state;
}
};
export default combineReducers({ countReducer });
Store.js
import React, { useReducer, createContext, useContext } from "react";
const initialState = {};
const Context = createContext(initialState);
const Provider = ({ children, reducers, ...rest }) => {
const defaultState = reducers(undefined, initialState);
if (defaultState === undefined) {
throw new Error("reducer's should not return undefined");
}
const [state, dispatch] = useReducer(reducers, defaultState);
return (
<Context.Provider value={{ state, dispatch }}>{children}</Context.Provider>
);
};
const combineReducers = reducers => {
const entries = Object.entries(reducers);
return (state = {}, action) => {
return entries.reduce((_state, [key, reducer]) => {
_state[key] = reducer(state[key], action);
return _state;
}, {});
};
};
const Connect = (mapStateToProps, mapDispatchToProps) => {
return WrappedComponent => {
return props => {
const { state, dispatch } = useContext(Context);
let localState = { ...state };
if (mapStateToProps) {
localState = mapStateToProps(state);
}
if (mapDispatchToProps) {
localState = { ...localState, ...mapDispatchToProps(dispatch, state) };
}
return (
<WrappedComponent
{...props}
{...localState}
state={state}
dispatch={dispatch}
/>
);
};
};
};
export { Context, Provider, Connect, combineReducers };
App.js
import React from "react";
import ContextStateManagement from "./ContextStateManagement";
import CounterUseReducer from "./CounterUseReducer";
import reducers from "./Reducers";
import { Provider } from "./Store";
import "./style.css";
export default function App() {
return (
<Provider reducers={reducers}>
<ContextStateManagement />
</Provider>
);
}
Component.js
import React from "react";
import { Connect } from "./Store";
const ContextStateManagement = props => {
return (
<>
<h3>Global Context: {props.count} </h3>
<button onClick={props.increment}>Global Increment</button>
<br />
<br />
<button onClick={props.decrement}>Global Decrement</button>
</>
);
};
const mapStateToProps = ({ countReducer }) => {
return {
count: countReducer.count
};
};
const mapDispatchToProps = dispatch => {
return {
increment: () => dispatch({ type: "INCREMENT" }),
decrement: () => dispatch({ type: "DECREMENT" })
};
};
export default Connect(mapStateToProps, mapDispatchToProps)(
ContextStateManagement
);

If you don't want your Parent component to re-render when state updates, then you are using the wrong state management pattern, flat-out. Instead you should use something like Redux, which removes "state" from the React component tree entirely, and allows components to directly subscribe to state updates.
Redux will allow only the component that subscribes to specific store values to update only when those values update. So, your Parent component and the Child component that dispatches the update action won't update, while only the Child component that subscribes to the state updates. It's very efficient!
https://codesandbox.io/s/simple-redux-example-y3t32

React component is updated only when either
Its own props is changed
state is changed
parent's state is changed
As you have pointed out state needs to be saved in the parent component and passed on to the context.
Your requirement is
Parent should not re-render when state is changed.
Only Child1 should re-render on state change
const SomeContext = React.createContext(null);
Child 1 and 2
const Child1 = () => {
const ctx = useContext(SomeContext);
console.log(`child1: ${ctx}`);
return <div>{ctx.value}</div>;
};
const Child2 = () => {
const ctx = useContext(UpdateContext);
console.log("child 2");
const onClickBtn = () => {
ctx.updateValue("updates");
};
return <button onClick={onClickBtn}>Update Value </button>;
};
Now the context provider that adds the state
const Provider = (props) => {
const [state, setState] = useState({ value: "Hello" });
const updateValue = (newValue) => {
setState({
value: newValue
});
};
useEffect(() => {
document.addEventListener("stateUpdates", (e) => {
updateValue(e.detail);
});
}, []);
const getState = () => {
return {
value: state.value,
updateValue
};
};
return (
<SomeContext.Provider value={getState()}>
{props.children}.
</SomeContext.Provider>
);
};
Parent component that renders both the Child1 and Child2
const Parent = () => {
// This is only logged once
console.log("render parent");
return (
<Provider>
<Child1 />
<Child2 />
</Provider>
);
};
Now for the first requirement when you update the state by clicking button from the child2 the Parent will not re-render because Context Provider is not its parent.
When the state is changed only Child1 and Child2 will re-render.
Now for second requirement only Child1 needs to be re-rendered.
For this we need to refactor a bit.
This is where reactivity comes. As long as Child2 is a child of Provider when ever the state changes it will also gets updated.
Take the Child2 out of provider.
const Parent = () => {
console.log("render parent");
return (
<>
<Provider>
<Child1 />
</Provider>
<Child2 />
</>
);
};
Now we need some way to update the state from Child2.
Here I have used the browser custom event for simplicity. You can use RxJs.
Provider is listening the state updates and Child2 will trigger the event when button is clicked and state gets updated.
const Provider = (props) => {
const [state, setState] = useState({ value: "Hello" });
const updateValue = (e) => {
setState({
value: e.detail
});
};
useEffect(() => {
document.addEventListener("stateUpdates", updateValue);
return ()=>{
document.addEventListener("stateUpdates", updateValue);
}
}, []);
return (
<SomeContext.Provider value={state}>{props.children}</SomeContext.Provider>
);
};
const Child2 = () => {
console.log("child 2");
const onClickBtn = () => {
const event = new CustomEvent("stateUpdates", { detail: "Updates" });
document.dispatchEvent(event);
};
return <button onClick={onClickBtn}>Update Value </button>;
};
NOTE: Child2 will not have access to context
I hope this helps let me know if you didn't understand anything.

Related

React: How to use multiple Contexts of the same type while allowing children to read data from all of them

I have a certain Context setup similar to this
const DataContext = createContext({ data: null });
const getData = (key) => {
switch(key) {
case 1:
return "Hello"
case 2:
return " World"
default:
return null
}
}
export const DataProvider = ({ id, children }) => {
const data = useMemo(() => {
return getData(id);
}, [id]);
return (
<DataContext.Provider
value={{
data,
}}
>
{children}
</DataContext.Provider>
);
};
export default DataContext
And child components that use it like this
const HelloComponent = () => {
return <DataProvider id={1}>
{
// children are components that useContext(DataContext) and expect data to be "Hello"
}
</DataProvider>
}
Now I need to do this
const HelloWorldComponent = () => {
return (
<DataProvider id={1}>
<DataProvider id={2}>
{
// children are components that need to read both Hello and World
}
</DataProvider>
</DataProvider>
);
};
Need to provide all parent context's data of one single Context definition to a set of children
I know useContext can only read the closest parent of a given ContextType, so I'm not sure of how to proceed with this.
You can't use two context providers of the same type and have children receive from both. The Context API is such that children components receive the context value from the closest context provider to them in the React tree.
You can, however, use a single provider that instead returns the getData function. Here's an example using a single DataProvider and a custom React hook to provide the "id" value.
Data.Context.js
import { createContext, useContext } from "react";
const DataContext = createContext({
getData: () => {}
});
const getData = (key) => {
switch (key) {
case 1:
return "Hello";
case 2:
return " World";
default:
return null;
}
};
export const useDataContext = (id) => useContext(DataContext).getData(id);
const DataProvider = ({ children }) => {
return (
<DataContext.Provider value={{ getData }}>{children}</DataContext.Provider>
);
};
export default DataProvider;
index.js
<DataProvider>
<App />
</DataProvider>
Child component
import { useDataContext } from "./Data.Context";
const Child = () => {
const data1 = useDataContext(1);
const data2 = useDataContext(2);
return (
<div>
<div>DataProvider 1: {data1}</div>
<div>DataProvider 2: {data2}</div>
</div>
)
}

Component not re-rendering after waiting for react context

I am checking to see if isFetchingData then don't render yet but its not re-rendering once isFetchingData is set to false. I have the useEffect in the context and i would hope that would re-render once isFetchingData is set to false. Any ideas?
When I refresh the page it renders with the data. So I think its to do with re-rendering.
I am using react context to get the data and exposing functions to filter that data and get me what i need.
Context:
import React, { useEffect, useState } from 'react';
import getAllEmployees from 'my-services/employee/getAllEmployees';
import { arrayOf, node, oneOfType } from 'prop-types';
export const EmployeeContext = React.createContext({
allEmployees: [],
getActiveEmployees: () => [],
getTerminatedEmployees: () => []
});
const EmployeesProvider = ({ children }) => {
const [isFetchingData, setIsFetchingData] = useState(true);
const [allEmployees, setAllEmployees] = useState({});
useEffect(() => {
getAllEmployees().then(
//doing something
).then(employees => {
setAllEmployees(employees);
setIsFetchingData(false);
});
}, [isFetchingData])
const context = {
isFetchingData,
allEmployees,
getActiveEmployees: () =>
allEmployees.filter(x => x.status === 'Current'),
getTerminatedEmployees: () =>
allEmployees.filter(x => x.status === 'Terminated')
};
return (
<EmployeeContext.Provider value={context}>{children}</EmployeeContext.Provider>
);
};
EmployeesProvider.propTypes = {
children: oneOfType([node, arrayOf(node)])
};
EmployeesProvider.defaultProps = {
children: undefined
};
export default EmployeesProvider;
Component:
import React, { useContext } from 'react';
import styled from 'styled-components';
import { EmployeeContext } from 'my-contexts/EmployeeContext';
import EmployeeCard from '../../../components/EmployeeCard';
const EmployeesTab = () => {
const {
getActiveEmployees,
getTerminatedEmployees,
isFetchingData
} = useContext(EmployeeContext);
let activeEmployees = [];
let terminatedEmployees = [];
if (!isFetchingData) {
activeEmployees = getActiveEmployees();
terminatedEmployees = getTerminatedEmployees();
}
if(isFetchingData) {
return <p>Loading</p>;
}
return (
<Outer>
<TopHeader>
<H3>Employees ({activeEmployees.length})</H3>
</TopHeader>
<Wrapper>
{activeEmployees.map(employee => {
return (
<EmployeeCard
id={employee.id}
guid={employee.guid}
firstName={employee.name.first}
lastName={employee.name.last}
jobTitle={employee.jobTitle}
/>
);
})}
</Wrapper>
<H3>Terminated employees({terminatedEmployees.length})</H3>
<Wrapper>
{terminatedEmployees.map(employee => {
return (
<EmployeeCard
id={employee.id}
guid={employee.guid}
firstName={employee.name.first}
lastName={employee.name.last}
jobTitle={employee.jobTitle}
/>
);
})}
</Wrapper>
</Outer>
);
};
export default EmployeesTab;
I think many problems may exist.
At first, please check whether whole component is closed by context Provider.
For example
<EmployeesProvider>
<EmployeesTab/>
<EmployeesProvider/>
Please check this problem.

A functional subcomponent doesn't rerender on props change

I have a very heavy (computationally) functional component (Parent) which doesn't have a state and has few Child sub-components with local state. Children are dependent only on props send from the Parent.
I pass a function to one of the children (ChildA) to change the value of a variable on the Parent.
This variable is one of the props of a different Child component (ChildB) which has a state based on that prop and updates it in useEffect hook.
The ChildB component does not re-render when the value passed as prop changes on the Parent component.
Sure, introducing state (useState hook) on Parent fixes this but re-renders the parent over and over and kills the performance as Parent has 500+ nested components which all get re-rendered.
Introducing some kind of a Store (Redux, MobX) would probably solve the issue but that would be an overkill.
A simplified example:
import React, { useEffect, useState } from "react";
export default function App() {
return <Parent />
}
const ChildA = ({ onAction }) => {
return <button onClick={onAction}>CLICK</button>;
};
const ChildB = ({ coreValue }) => {
const [value, setValue] = useState(0);
useEffect(() => {
setValue(coreValue);
}, [coreValue]);
return <div>My value: {value}</div>;
};
const Parent = () => {
let calculatedValue = 0;
const changeValue = () => {
calculatedValue += Math.random();
};
return (
<div>
<ChildA onAction={changeValue} />
<ChildB coreValue={calculatedValue} />
</div>
);
};
You can test the code here: https://codesandbox.io/s/vigilant-wave-r27rg
How do I re-render only ChildB on props change?
You have to store the value in parent component state and just send the parent component state value to the ChildB, there you don't need to maintain state and useEffect hook to catch the change. See the code here: https://codesandbox.io/s/adoring-chatelet-sjjfs
import React, { useState } from "react";
export default function App() {
return <Parent />;
}
const ChildA = ({ onAction }) => {
return <button onClick={onAction}>CLICK</button>;
};
const ChildB = ({ coreValue }) => {
return <div>My value: {coreValue}</div>;
};
const Parent = () => {
const [value, setValue] = useState(0);
const changeValue = () => {
setValue(value + Math.random());
};
return (
<div>
<ChildA onAction={changeValue} />
<ChildB coreValue={value} />
</div>
);
};
React's useCallback and memo prevent's unnecessary re-rendering. Note that ChildA doesn't re-render regardless of the number of times the Parent or ChildB state's changes. Also, your current example doesn't need useState / useEffect in ChildB
https://codesandbox.io/s/usecallback-and-memo-ptkuj
import React, { useEffect, useState, memo, useCallback } from "react";
export default function App() {
return <Parent />;
}
const ChildA = memo(({ onAction }) => {
console.log("ChildA rendering");
return <button onClick={onAction}>CLICK</button>;
});
const ChildB = memo(({ coreValue }) => {
const [value, setValue] = useState(0);
useEffect(() => {
setValue(coreValue);
}, [coreValue]);
return <div>My value: {value}</div>;
});
const Parent = () => {
const [calculatedValue, setCalculatedValue] = useState(0);
const changeValue = useCallback(() => {
setCalculatedValue(c => (c += Math.random()));
}, []);
return (
<div>
<ChildA onAction={changeValue} />
<ChildB coreValue={calculatedValue} />
</div>
);
};

The action is undefined or invisible even if it seems written properly

I have to use useDispatch() for my toggle buttons so I have to refractor them from react to redux state. I was following the tutorial of basics of Redux and I think I have done that properly but when I try to at least useSelector to display the redux'state of button it doesnt show anything.
So here is my code:
// types.js in actions folder
export const TOGGLE = "TOGGLE";
// buttonActions in actions folder
export const toggle = () => {
return {
type: 'TOGGLE'
};
};
// buttonReducer in reducers folder
const buttonReducer = (state = true, action) => {
switch(action.type) {
case 'TOGGLE':
return !state;
default:
return state;
};
};
export default buttonReducer;
And the buttonReducer is imported into combineReducers which go to store.
The component code:
import React, { useState, useEffect } from 'react'
import isloff from './mainpage_imgs/isloff.png'
import islon from './mainpage_imgs/islon.png'
import PropTypes from "prop-types";
import { connect, useDispatch, useSelector } from "react-redux";
import { toggle } from '../../actions/buttonActions'
const Islbutton = props => {
const [open, setOpen] = useState(true);
const [role, setRole] = useState('');
useEffect(() => {
if (props.auth.user)
{
setRole(props.auth.user.role);
}
}, []);
const test = useSelector(state => state.button);
const checkRole = (role) => {
if (role === 'Menager' || role === 'Technolog')
{
return true }
else
{
return false
};
}
const toggleImage = () => {
if(checkRole(role)) {
setOpen(!open)
};
}
const getImageName = () => open ? 'islOnn' : 'islOfff'
const dispatch = useDispatch();
return(
<div>
<img style={islplace} src={open ? islon : isloff }
onClick={()=> dispatch(toggle())} />
</div>
);
}
Islbutton.propTypes = {
button: PropTypes.func.isRequired,
auth: PropTypes.obj.isRequired
};
const mapStateToProps = state => ({
button: state.button,
auth: state.auth
});
export default connect(mapStateToProps, {}), (Islbutton);
Based on your latest comments and my understanding of your use case I may suggest following distilled approach:
//dependencies
const { render } = ReactDOM,
{ createStore } = Redux,
{ connect, Provider } = ReactRedux
//action creators
const SET_ROLE = 'SET_ROLE',
MANAGER_APPROVED = 'MANAGER_APPROVED',
setRole = role => ({type:SET_ROLE, role}),
mngAppr = () => ({type:MANAGER_APPROVED})
//initial state, reducer, store
const initialState = {role:'Technolog', approved:false},
appReducer = (state=initialState, action) => {
switch(action.type){
case SET_ROLE : {
const {role} = state,
{role: newRole} = action
return {...state, role: newRole}
}
case MANAGER_APPROVED : {
const {approved} = state
return {...state, approved: !approved}
}
default: return state
}
},
store = createStore(appReducer)
//ui component to emulate toggling roles
const SwitchRoles = ({currentRole, switchRole}) => (
<div>
<label><input type="radio" name="role" value="Manager" onChange={e => switchRole(e.target.value)} />Manager</label>
<label><input type="radio" name="role" value="Technolog" onChange={e => switchRole(e.target.value)} />Technolog</label>
</div>
)
//connect radio buttons click to togling roles action
const mapDispatch = dispatch => ({switchRole: role => dispatch(setRole(role))}),
SwitchRolesContainer = connect(null,mapDispatch)(SwitchRoles)
//ui component to toggle 'approved' within global state
const ToggleApprove = ({onApprove,isManager}) => (
<button onClick={onApprove} disabled={!isManager}>Toggle</button>
)
//connect onToggle handler to dispatching 'toggle' action
const mapStateToProps = ({role}) => ({isManager: role == 'Manager'}),
mapDispatchToProps = dispatch => ({onApprove: () => dispatch(mngAppr())}),
ToggleApproveContainer = connect(mapStateToProps, mapDispatchToProps)(ToggleApprove)
//ui component to display current state of 'open'
const IsApproved = ({isApproved}) => <div>{isApproved ? 'Approved by manager' : 'Not approved by manager'}</div>
//attach isOpen prop to global 'open' variable
const mapState = ({approved}) => ({isApproved: approved}),
IsApprovedContainer = connect(mapState)(IsApproved)
//render the app
render (
<Provider store={store}>
<SwitchRolesContainer />
<IsApprovedContainer />
<ToggleApproveContainer />
</Provider>,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.1.3/react-redux.min.js"></script><div id="root"></div>
Hopefully, it gives a piece of mind about toggling global variables and mapping their values onto local components state.

Issues with useReducer not synchronously updating the state

According to React docs :
useReducer is usually preferable to useState when you have complex
state logic that involves multiple sub-values or when the next state
depends on the previous one.
1. can somebody explain me why useReducer is not updating the state synchronously ?
const reducer = (state, action) => {
if( action.type === 'ADD_VALUE') {
console.log(`STATE IN REDUCER`, [...state, action.path]) // => ["1.1"]
return [...state, action.path]
}
}
const [state, dispatch] = useReducer(reducer, [])
<input type="button" onClick={() => {
dispatch({ type: 'ADD_VALUE', path: "1.1"})
console.log(`STATE`, state) // => []
// here i want to do some stuff based on the lastest updated state (["1.1"] and not [])
// for example dispatch an action with redux
}}/>
2. How can I do some stuff (dispatch a redux action) based on the lastest updated state (["1.1"] and not []) ?
Use useEffect to access the state correctly. You could add some safe-guarding if you want something invoking if a certain criterion is hit.
If you want to access your reducer across components, you can store the reducer using Context API. Look below for an example. You can see the reducer being injected into the Context on the parent component and then two child components that a) dispatches an action b) receives the update from the action.
1. Example of context reducer to use across multiple components
import React from "react";
import ReactDOM from "react-dom";
const Application = React.createContext({
state: null,
dispatch: null
});
function ActionComponent() {
const { dispatch } = React.useContext(Application);
return (
<div>
<div>Action Component</div>
<button onClick={() => dispatch("lol")}>Do something</button>
</div>
);
}
function ListenerComponent() {
const { state } = React.useContext(Application);
React.useEffect(
() => {
console.log(state);
},
[state]
);
return <div>Listener Component</div>;
}
function App() {
const [state, dispatch] = React.useReducer(function(state = [], action) {
return [...state, action];
});
return (
<Application.Provider value={{ state, dispatch }}>
<div className="App">
<ActionComponent />
<ListenerComponent />
</div>
</Application.Provider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
2. Example of local reducer without using Application Context
const reducer = (state, action) => {
if( action.type === 'ADD_VALUE') {
return [...state, action.path]
}
}
const [state, dispatch] = useReducer(reducer, [])
React.useEffect(() => {
console.log(state);
}, [state]);
<input type="button" onClick={() => {
dispatch({ type: 'ADD_VALUE', path: "1.1"})
}}/>

Categories