DEV Community

Discussion on: 6 use cases of the useEffect ReactJS hook

Collapse
 
xabitrigo profile image
xabitrigo

IMHO the following use cases do not really need the useEffect, because those values are derived state that can be calculated on the render phase.

  • Running on state change: validating input field
const UseCaseInputValidation = props => {
    const [input, setInput] = useState('');
    const isValid = (input.length < 5 || /\d/.test(input))

    return (/* jsx that uses isValid */ );
};
Enter fullscreen mode Exit fullscreen mode
  • Running on state change: live filtering
const array = [
    // array data
];

const UseCaseLiveFilter = props => {
    const [inputValue, setInputValue] = useState('');
    const [inputType, setInputType] = useState('');
    const filteredArray = array
        .filter(item => item.value.includes(inputValue))
        .filter(item => item.type.includes(inputType))
    ;

    const inputValueHandler = e => {
        setInputValue(e.target.value);
    };

    const inputTypeHandler = e => {
        setInputType(e.target.value);
    };

    // Prepare array to be rendered
    // FIXED key
    const listItems = filteredArray.map((item) =>
        <Fragment key={item.key}>
            <tr>
                <td style={{ border: '1px solid lightgray', padding: '0 1rem' }}>{item.type}</td>
                <td style={{ border: '1px solid lightgray', padding: '0 1rem' }} > {item.value}</td>
            </tr >
        </Fragment>
    );

    return (/* jsx that uses filteredArray */);
};
Enter fullscreen mode Exit fullscreen mode
  • Running on props change: update paragraph list on fetched API data update
const BaconParagraphs = props => {
    // WRONG key
    const baconParagraphText = props.chopBacon
        .map(piece => <p key={Math.random()}>{piece}</p>)
    ;

    return (
        <>
            <p>Number of paragraphs: {baconParagraphText.length}</p>
            {baconParagraphText}
        </>
    );
};
Enter fullscreen mode Exit fullscreen mode

Also note that for every map that returns jsx, we should use the key prop in its first jsx element. And it has to be a unique value that doesn't change between renders. Using Math.random(), like you do in this last example, defeats the purpose of the key prop.

Collapse
 
shoaibzaak profile image
shoaib zaki

because the we want the make the codition there when a user clicked on the button the n there will be change in the the state and and we will show paraticular result on the change of the state useeffect is used there to ensure that particular type of trick