I have a React decorator component which is connected to the Redux store and I'm using it to dispatch an action (which is used to get some data from an API endpoint) and show a Loader Component. Then, once the data is fetched, it shows a wrapped component.
It looks like this:
const loadData = LoaderComponent => WrappedComponent => {
class loadDataHOC extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const {fetchData, isLoading} = this.props;
if(!isLoading){
fetchData();
}
}
render() {
const {data, isLoading} = this.props;
if (isLoading) {
return <LoaderComponent />;
}
return <WrappedComponent data={data} />;
}
}
const mapStateToProps = state => {
return {
data: getData(state),
isLoading: getIsLoading(state)
};
};
const mapDispatchToProps = dispatch => bindActionCreators({getData}, dispatch);
return connect(mapStateToProps, mapDispatchToProps)(loadDataHOC);
};
export default loadData;
This component is meant to be reusable so I can use it to fetch and store the same data from different presentational components. What I'd like to do now is to use this component in two different parts of the same view, like this:
const EnhancedComponent1 = loadData(Spinner)(MyPresentationalComponent1);
const EnhancedComponent2 = loadData(Spinner)(MyPresentationalComponent2)
The problem is that the two EnhancedComponent both fire fetchData() because they are mounted together and therefore the isLoading prop is false in both the function calls.
For now I've solved it by checking the isLoading prop inside the action so the second call is immediately stopped, but I'm not sure if this is the best way to deal with it.
const getData = () => (dispatch, getState) => {
if(getIsLoading(getState())) {
return;
}
dispatch(getData());
...
};
Another way to do it would be to create only one parent enhanced component just to fetch the data and then two presentational components down the tree that only access the state, but I'd like to fetch the data as close as possible to the presentational component.
Thanks
Related
I have this class component that returns state populated perfectly using Redux store:
class TopRatedComponent extends Component {
componentDidMount() {
this.props.fetchTopRatedMovies();
}
render() {
const IMG_API_ROOT_LINK = 'https://image.tmdb.org/t/p/w500';
const { topRatedMovies, loading, error } = this.props;
return (
<div>
{loading && <div>LOADING...</div>}
{error && <div>{error}</div>}
<Container className="p-4" onScroll={this.onScroll}>
<div className="text-center">
{
topRatedMovies.results && topRatedMovies.results.map(topRated => (
<p>{topRated.title}</p>
))
}
</div>
</Container>
</div>
);
}
}
const mapStateToProps = state => {
const { topRatedMovies, loading, error } = state.topRatedMovies;
return {
topRatedMovies,
loading,
error
};
};
export default connect(
mapStateToProps,
{
fetchTopRatedMovies
}
)(TopRatedComponent);
However, when I switch the above class component into a functional component below so I can use ReactJS hooks with my code, but the state is always empty.
const TopRatedComponent = () => {
const [count, setCount] = useState(0);
const [topRated, settopRated] = useState([]);
useEffect(() => {
settopRated(this.props.fetchTopRatedMovies)
}, [this.props.fetchTopRatedMovies])
const allState = useSelector((state) => state)
console.log('CHOF: ' + JSON.stringify(allState));
return (
<div>
WOOOOOOOW....
</div>
)
};
You haven't correctly transformed your class-based component into equivalent functional component.
Following are the problems in your functional component:
In class component, you receive the fetchTopRatedMovies action creator as a prop and you dispatch it from the componentDidMount lifecycle method. In functional component, you are not dispatching it.
To dispatch the action in functional components, use useDispatch() hook and use useEffect hook to dispatch this action after component has mounted.
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
const TopRatedComponent = () => {
...
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchTopRatedMovies());
}, []);
...
};
In class components, you access props object using this but in functional components, props object is passed as an argument. So, you can directly access it using the parameter name you use for the props object
const TopRatedComponent = (props) => {
console.log(props);
// code
};
Data that your component receives as props from the redux store using mapStateToProps function and connect higher order component, can be accessed using useSelector hook in functional components.
import { useSelector } from "react-redux";
const TopRatedComponent = () => {
const {
topRatedMovies,
loading,
error
} = useSelector(state => state.topRatedMovies);
// code
};
Note: You can also use connect higher-order component and mapStateToProps to connect your functional component with the redux store.
For details of how to use hooks with react-redux, see: react-redux - Hooks
this doesn't work the same way in a functional component. You need to pull props from your function arguments instead.
const TopRatedComponent = (props) => {
const [count, setCount] = useState(0);
const [topRated, settopRated] = useState([]);
useEffect(() => {
settopRated(props.fetchTopRatedMovies)
}, [props.fetchTopRatedMovies])
const allState = useSelector((state) => state)
console.log('CHOF: ' + JSON.stringify(allState));
return (
<div>
WOOOOOOOW....
</div>
)
};
Arrow functions don't have their own context (this variable). I assume that fetchTopRatedMovies is an action (thunk) that fetches data from an API and set it to a global state. In this case, you need to also get that data using Redux hooks (if the version you are using supports it).
const TopRatedComponent = ({ fetchTopRatedMovies }) => {
const [count, setCount] = useState(0);
// this is written according to your `mapStateToProps` function.
const { topRatedMovies, loading, error } = useSelector(({topRatedMovies}) => topRatedMovies);
useEffect(() => {
fetchTopRatedMovies();
}, [fetchTopRatedMovies])
if (loading) return 'LOADING...';
if (error) return <div>{error.message}</div>
return (
<div>
etc...
</div>
)
};
I use React context with hooks as a state manager for my React app. Every time the value changes in the store, all the components re-render.
Is there any way to prevent React component to re-render?
Store config:
import React, { useReducer } from "react";
import rootReducer from "./reducers/rootReducer";
export const ApiContext = React.createContext();
export const Provider = ({ children }) => {
const [state, dispatch] = useReducer(rootReducer, {});
return (
<ApiContext.Provider value={{ ...state, dispatch }}>
{children}
</ApiContext.Provider>
);
};
An example of a reducer:
import * as types from "./../actionTypes";
const initialState = {
fetchedBooks: null
};
const bookReducer = (state = initialState, action) => {
switch (action.type) {
case types.GET_BOOKS:
return { ...state, fetchedBooks: action.payload };
default:
return state;
}
};
export default bookReducer;
Root reducer, that can combine as many reducers, as possible:
import userReducer from "./userReducer";
import bookReducer from "./bookReducer";
const rootReducer = ({ users, books }, action) => ({
users: userReducer(users, action),
books: bookReducer(books, action)
});
An example of an action:
import * as types from "../actionTypes";
export const getBooks = async dispatch => {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1", {
method: "GET"
});
const payload = await response.json();
dispatch({
type: types.GET_BOOKS,
payload
});
};
export default rootReducer;
And here's the book component:
import React, { useContext, useEffect } from "react";
import { ApiContext } from "../../store/StoreProvider";
import { getBooks } from "../../store/actions/bookActions";
const Books = () => {
const { dispatch, books } = useContext(ApiContext);
const contextValue = useContext(ApiContext);
useEffect(() => {
setTimeout(() => {
getBooks(dispatch);
}, 1000);
}, [dispatch]);
console.log(contextValue);
return (
<ApiContext.Consumer>
{value =>
value.books ? (
<div>
{value.books &&
value.books.fetchedBooks &&
value.books.fetchedBooks.title}
</div>
) : (
<div>Loading...</div>
)
}
</ApiContext.Consumer>
);
};
export default Books;
When the value changes in Books component, another my component Users re-renders:
import React, { useContext, useEffect } from "react";
import { ApiContext } from "../../store/StoreProvider";
import { getUsers } from "../../store/actions/userActions";
const Users = () => {
const { dispatch, users } = useContext(ApiContext);
const contextValue = useContext(ApiContext);
useEffect(() => {
getUsers(true, dispatch);
}, [dispatch]);
console.log(contextValue, "Value from store");
return <div>Users</div>;
};
export default Users;
What's the best way to optimize context re-renders? Thanks in advance!
Books and Users currently re-render on every cycle - not only in case of store value changes.
1. Prop and state changes
React re-renders the whole sub component tree starting with the component as root, where a change in props or state has happened. You change parent state by getUsers, so Books and Users re-render.
const App = () => {
const [state, dispatch] = React.useReducer(
state => ({
count: state.count + 1
}),
{ count: 0 }
);
return (
<div>
<Child />
<button onClick={dispatch}>Increment</button>
<p>
Click the button! Child will be re-rendered on every state change, while
not receiving any props (see console.log).
</p>
</div>
);
}
const Child = () => {
console.log("render Child");
return "Hello Child ";
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<div id="root"></div>
Optimization technique
Use React.memo to prevent a re-render of a comp, if its own props haven't actually changed.
// prevents Child re-render, when the button in above snippet is clicked
const Child = React.memo(() => {
return "Hello Child ";
});
// equivalent to `PureComponent` or custom `shouldComponentUpdate` of class comps
Important: React.memo only checks prop changes (useContext value changes trigger re-render)!
2. Context changes
All context consumers (useContext) are automatically re-rendered, when the context value changes.
// here object reference is always a new object literal = re-render every cycle
<ApiContext.Provider value={{ ...state, dispatch }}>
{children}
</ApiContext.Provider>
Optimization technique
Make sure to have stable object references for the context value, e.g. by useMemo Hook.
const [state, dispatch] = useReducer(rootReducer, {});
const store = React.useMemo(() => ({ state, dispatch }), [state])
<ApiContext.Provider value={store}>
{children}
</ApiContext.Provider>
Other
Not sure, why you put all these constructs together in Books, just use one useContext:
const { dispatch, books } = useContext(ApiContext);
// drop these
const contextValue = useContext(ApiContext);
<ApiContext.Consumer> /* ... */ </ApiContext.Consumer>;
You also can have a look at this code example using both React.memo and useContext.
I believe what is happening here is expected behavior. The reason it renders twice is because you are automatically grabbing a new book/user when you visit the book or user page respectively.
This happens because the page loads, then useEffect kicks off and grabs a book or user, then the page needs to re-render in order to put the newly grabbed book or user into the DOM.
I have modified your CodePen in order to show that this is the case.. If you disable 'autoload' on the book or user page (I added a button for this), then browse off that page, then browse back to that page, you will see it only renders once.
I have also added a button which allows you to grab a new book or user on demand... this is to show how only the page which you are on gets re-rendered.
All in all, this is expected behavior, to my knowledge.
I tried to explain with different example hope that will help.
Because context uses reference identity to determine when to re-render, that could trigger unintentional renders in consumers when a provider’s parent re-renders.
for example: code below will re-render all consumers every time the Provider re-renders because a new object is always created for value
class App extends React.Component {
render() {
return (
<Provider value={{something: 'something'}}>
<Toolbar />
</Provider>
);
}
}
To get around this, lift the value into the parent’s state
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: {something: 'something'},
};
}
render() {
return (
<Provider value={this.state.value}>
<Toolbar />
</Provider>
);
}
}
This solution is used to prevent a component from rendering in React is called shouldComponentUpdate. It is a lifecycle method which is available on React class components. Instead of having Square as a functional stateless component as before:
const Square = ({ number }) => <Item>{number * number}</Item>;
You can use a class component with a componentShouldUpdate method:
class Square extends Component {
shouldComponentUpdate(nextProps, nextState) {
...
}
render() {
return <Item>{this.props.number * this.props.number}</Item>;
}
}
As you can see, the shouldComponentUpdate class method has access to the next props and state before running the re-rendering of a component. That’s where you can decide to prevent the re-render by returning false from this method. If you return true, the component re-renders.
class Square extends Component {
shouldComponentUpdate(nextProps, nextState) {
if (this.props.number === nextProps.number) {
return false;
} else {
return true;
}
}
render() {
return <Item>{this.props.number * this.props.number}</Item>;
}
}
In this case, if the incoming number prop didn’t change, the component should not update. Try it yourself by adding console logs again to your components. The Square component shouldn’t rerender when the perspective changes. That’s a huge performance boost for your React application because all your child components don’t rerender with every rerender of their parent component. Finally, it’s up to you to prevent a rerender of a component.
Understanding this componentShouldUpdate method will surely help you out!
Iam trying to understand and learn how to pass around data as props to other components to use. Iam trying to build a top-level hierarchy where the API Request is made in a class at top level and then the result is passed around to child components to be used as props and then in states.
The problem is that when i pass the result i get "Object Promise" in my child component. How do I access the data sent as props to child components?
As you can see in my App.js in my render() method that i created a component of the class API and pass the result from the fetchData() method as parameter to the component.
In my API.js class i used console.log to check the result but
the result i get from the logs are:
line 5: {dataObject: Promise}
line 10: undefined
App.js:
import API from './API';
class App extends Component {
componentDidMount(){
this.fetchData();
}
fetchData(){
const url = "https://randomuser.me/api/?results=50&nat=us,dk,fr,gb";
return fetch(url)
.then(response => response.json())
.then(parsedJSON => console.log(parsedJSON.results))
.catch(error => console.log(error));
}
render() {
return (
<div className="App">
<API dataObject={this.fetchData()}/>
</div>
);
}
}
export default App;
API.js
import React from 'react';
class API extends React.Component{
constructor(props){
console.log(props);
super(props);
this.state = {
dataObj:props.dataObject
};
console.log(this.state.dataObject)
}
render() {
return(
<p>""</p>
)
}
}
export default API;
Try changing App.js to this:
import API from './API';
class App extends Component {
componentDidMount(){
this.fetchData();
}
fetchData(){
const url = "https://randomuser.me/api/?results=50&nat=us,dk,fr,gb";
return fetch(url)
.then(response => response.json())
.then(parsedJSON => this.setState({results: parsedJSON.results}))
.catch(error => console.log(error));
}
render() {
return (
<div className="App">
<API dataObject={this.state.results}/>
</div>
);
}
}
export default App;
This makes sure you fetch the data in componentDidMount and it now uses state to store the data which then will be passed into your API component.
If anyone is looking for an answer using Hooks then this might help.
App.js
import API from './API';
function App(props) {
const [result, setResult] = React.useState({});
// similar to componentDidMount
React.useEffect(() => {
this.fetchData();
}, []);
fetchData() {
const url = "https://randomuser.me/api/?results=50&nat=us,dk,fr,gb";
fetch(url)
.then(response => setResult(response.json()))
.catch(error => console.log(error));
}
return (
<div className="App">
<API dataObject={result}/>
</div>
);
}
export default App;
API.js
import React from "react";
function API(props) {
const [result, setResult] = React.useState(props.dataObject);
React.useEffect(() => {
setResult(result);
}, [result]);
return <p>{result}</p>;
}
export default API;
Hope it helps! And let me know if anything is incorrect.
You should fetch data in componentDidMount and not in render. Fetching the data within render causes the API request to be repeated, every time the DOM is re-rendered by react.js.
After making the GET request to the API endpoint, first parse the data into a javascript object, then set the results to state using this.setState from within your component.
From there, you may pass the data held in state to child components as props in the render function.
For example:
const App = (props) =>
<ChildComponent />
class ChildComponent extends React.Component {
constructor(props){
super(props);
this.state = {
results: []
}
}
componentDidMount(){
fetch('/api/endpoint')
.then(res => res.json())
.then(results => this.setState({results})
}
render(){
return <GrandchildComponent {...this.state} />
}
}
const GrandchildComponent = (props) =>
<div>{props.results}</div>
I written a custom logic for handling async route loading bundles in react-router-dom .v4. It's work perfectly. But also I heard about useful package with nice API to do the same, like React-Loadable. It has one problem, I cannot get the props/state pushed from Redux on the mount of the component throw this package.
My code is rewritten from the custom style to react-loadable style in two examples below. The last one is react-loadable version, that does not throw state/props.
My personal code:
const asyncComponent = getComponent => {
return class AsyncComponent extends React.Component {
static Component = null;
state = { Component: AsyncComponent.Component };
componentWillMount() {
const { Component } = this.state
if (!Component) {
getComponent().then(({ default: Component }) => {
const { store } = this.props // CAN GET THE REDUX STORE
AsyncComponent.Component = Component;
this.setState({ Component });
});
}
}
render() {
const { Component } = this.state;
if (Component) {
return <Component {...this.props} />
}
return null;
}
};
};
export default withRouter(asyncComponent(() => import(/* webpackChunkName: "chunk_1" */ './containers/Component')))
The same code, but with React-Loadable:
const Loading = () => {
return <div>Loading...</div>;
}
const asyncComponent = Loadable({
loader: () => import(/* webpackChunkName: "" */ './containers/Component')
.then(state => {
const { store } = this.props // CANNOT GET THE REDUX STORE!!
}),
loading: Loading
})
export default withRouter(asyncComponent)
To get the state from Redux store via Provider you should place your asyncComponent in Stateful Component wrapper, like you do in your custom async logic (1st case).
It because Loadable library returns you asyncComponent like a function, not a constructor, that way he cannot get access to current Redux store. So, the working solution will be the next:
const Loading = () => {
return <div>Loading...</div>;
}
const asyncComponent = Loadable({
loader: () => import(/* webpackChunkName: "" */ './containers/Component')
.then(state => {
const { store } = this.props // YOU WILL GET THE REDUX STORE!!
}),
loading: Loading
})
class asyncComponentWrapper extends Component{ // Component wrapper for asyncComponent
render() {
return <asyncComponent {...this.props} />
}
}
export default withRouter(asyncComponentWrapper)
P.S.
I do not know what you try to do, but in case how to make reducer injection inside the current store (probably it's exactly what you trying to do), you need to include you Redux store explicitly by import, not from the Provider state.
Going through the react-redux docs, I'm trying to understand why the
todo example uses connect and mapDispatchToProps vs why the reddit example uses a more traditional render method & passing the dispatch through a handler as props to the child component. Is there a reason for this? I can only guess that it's because the former example has a container component correspond to only one presentational component whereas the latter example's container component contains two presentational components so it would not make sense to use connect (nor is it possible) on two components.
todo example :
const getVisibleTodos = (todos, filter) => {
...
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
reddit example:
class App extends Component {
...
handleChange(nextReddit) {
this.props.dispatch(selectReddit(nextReddit))
}
...
render() {
...
return (
<div>
<Picker value={selectedReddit}
onChange={this.handleChange}
options={[ 'reactjs', 'frontend' ]} />
<p>
...
It's perfectly okay to pass dispatch to your component unless you don't want your component to misuse the dispatch function and dispatch actions that are not supposed to be dispatched from that component!
If you want to limit your component, you don't want to pass dispatch directly to the component. You'll want to pass specific action creators through mapDispatchToProps.
I think it boils down to coding standards, really. If you decide to be strict on your components and not allow them to directly dispatch any action, you can use mapDispatchToProps to pass only specific action creators.
Bonus: In the first example, you're passing (id) => dispatch(toggleTodo(id)) function to your component. Try using bindActionCreators from redux instead of manually creating that function! Good luck.
UPDATE
export const dataLoadRequest = () => {
return {
type: 'DATA_LOAD_REQUEST',
}
}
In your Component.js file, you need to import two things.
import { dataLoadRequest } from 'actions.js';
import { bindActionCreators } from 'redux';
class Component extends React.Component{
...
componentDidMount(){
this.props.actions.dataLoadRequest();
}
...
}
const mapStateToProps = (state) => ({
...
});
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(dataLoadRequest, dispatch)
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Component);